Windows Tech Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Monday, 26 November 2012

It's Scripting Time Again! AD Server Descriptions

Posted on 20:07 by Unknown
This issue has come up a LOT in my career, but I don't know why.  It seems like something that Microsoft should address with some "feature" or utility or something.  What I'm blabbering about is updating the description for each Active Directory server account to match whatever the local computer description is.  The local computer description is what you see (and can update) from the Computer "Properties" form.

Local Computer Description

Active Directory Computer Description

It came up again tonight when a friend (called asking for help.  I happened to have the pieces of code on my server and glued them together in a few minutes (the mess below).  Every time I do something like this, I see horrifically bad coding habits from years past and do my best to clean them up before sharing them.

Is this Earth-shatteringly unique?  No.  Is it the only script of its kind? No.  Can you find alternatives on the web that will do just as well?  Absolutely.  If I get a little spare time, I will try to post this in PowerShell format (unless you want to submit that and I will post it, giving you full credit).

In any case, I hope this helps someone out there.  Read the WARNING and DISCLAIMER at the bottom!

'****************************************************************
' Filename..: server_descriptions.vbs
' Author....: David M. Stein
' Date......: 11/26/2012
' Purpose...: update AD computer descriptions from local descriptions
' Usage.....: cscript server_descriptions.vbs >output.log
' (note: the above redirect to output.log is optional)
'****************************************************************

Set objRootDSE = GetObject("LDAP://rootDSE")
ldapRoot = objRootDSE.Get("defaultNamingContext")

Const ADS_SCOPE_SUBTREE = 2
Const E_ADS_PROPERTY_NOT_FOUND = &h8000500D

' parse out NetBIOS domain name (e.g. "CONTOSO.COM")
nbDomain = Mid(Split(ldapRoot,",")(0),4)

wscript.echo "info: LDAP root is " & ldapRoot
wscript.echo "info: NetBIOS domain is " & nbDomain

serverlist = GetServerList()

For each strServer in Split(serverlist, ",")
wscript.echo "server_name...: " & strServer
strOUpath = ComputerOU(strServer)
localDesc = GetLocalDescription(strServer)
domainDesc = ADComputerDescription(strOUpath)

If localDesc = "" Then
localDesc = "NOT_DEFINED"
End If

wscript.echo "ou_path.......: " & strOUPath
wscript.echo "local_descrip.: " & localDesc
wscript.echo "domain_descrip: " & domainDesc

If localDesc <> "NOT_DEFINED" Then
try = ChangeADDescription(strOUPath, localDesc)
wscript.echo "desc_updated..: " & try

End If

wscript.echo "----------------------------------------"
Next

'----------------------------------------------------------------
' function: get list of servers from domain using OS captions
'----------------------------------------------------------------

Function GetServerList()
Dim conn, cmd, query, retval : retval = ""
Dim rs, strOS, strName, counter : counter = 0

wscript.echo "info: querying server names from active directory..."

Set cmd = CreateObject("ADODB.Command")
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "Active Directory Provider"
cmd.ActiveConnection = conn
  query = ";(objectCategory=computer);" & _
"name,distinguishedName,operatingSystem;subtree"

cmd.CommandText = query
cmd.Properties("Page Size") = 100
cmd.Properties("Timeout") = 30
cmd.Properties("Cache Results") = False

Set rs = cmd.Execute

Do Until rs.EOF
strOS = rs.Fields("operatingSystem").value
If InStr(UCase(strOS), "SERVER") > 0 Then
strName = rs.Fields("name").value
If retval <> "" Then
If InStr(retval, strName) < 1 Then
retval = retval & "," & strName
counter = counter + 1
End If
Else
retval = strName
counter = counter + 1
End If
End If
rs.MoveNext
Loop

rs.Close
conn.Close
Set rs = Nothing
Set cmd = Nothing
Set conn = Nothing

wscript.echo "info: " & counter & " servers were found"
GetServerList = retval

End Function

'----------------------------------------------------------------
' function: get current computer OU from active directory
'----------------------------------------------------------------

Function ComputerOU(netBiosName)
Dim objConnection, objCommand, objRecordSet, strQuery
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
strQuery = "Select ADsPath From 'LDAP://" & ldapRoot & _
"' WHERE objectCategory='computer'" & _
" AND name='" & netBiosName & "'"

On Error Resume Next
objCommand.CommandText = strQuery
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
strResult = objRecordSet.Fields("ADsPath").Value
objRecordSet.MoveNext
Loop
ComputerOU = strResult
End Function

'----------------------------------------------------------------
' description: get local description from remote computer via WMI
'----------------------------------------------------------------

Function GetLocalDescription(strName)
Dim objWMI, colItems, objItem
  Dim query, retval : retval = ""
  On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & strName & "\root\CIMV2") 
  If err.Number = 0 Then
    query = "SELECT * FROM Win32_OperatingSystem"
Set colItems = objWMIService.ExecQuery(query,,48)
For Each objItem in colItems
retval = objItem.Description
Next
If IsNull(retval) or Trim(retval) = "" Then
retval = ""
End If
  Else
    wscript.echo "error: " & strName & " is offline or inaccessible"
  End If
GetLocalDescription = retval
End Function

'----------------------------------------------------------------
' function: get AD computer description
'----------------------------------------------------------------

Function ADComputerDescription(strLDAP)
Dim objComputer, retval, try, ldapstring
ldapstring = strLDAP
On Error Resume Next
Set objComputer = GetObject(ldapstring)
try = objComputer.Get("description")
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
retval = ""
Err.Clear
Else
retval = try
End If
ADComputerDescription = retval
End Function

'----------------------------------------------------------------
' function: set AD computer description (limit 48 chars)
' refer to: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394239(v=vs.85).aspx
'----------------------------------------------------------------

Function ChangeADDescription(strLdapName, strDesc)
Dim objPC, retval
wscript.echo "info: modifying domain description..."
On Error Resume Next
Set objPC = GetObject(strLdapName)
objPC.Description = strDesc
objPC.SetInfo
retval = err.Number
If retval <> 0 Then
retval = retval & " / " & err.Description
Else
retval = "SUCCESS"
End If
Set objPC = Nothing
ChangeADDescription = retval
End Function

Warning

This script example includes MINIMAL error handling.  Always TEST, TEST, TEST, and when you think it works properly, TEST it some more.

Disclaimer

Use this script code AT YOUR OWN RISK.  Always test thoroughly in an isolated "test" or "development" environment to avoid negatively impacting production computers.  The author assumes/accepts NO LIABILITY for any direct or derivative use or consequential damages, however, the author wouldn't mind a little constructive feedback if it helps you in any way.
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in active directory, computers, ldap, network administration, programming, scripting, servers, vbscript, windows server, wmi | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Voting Time: Help Me Out?
    I need to get a better view of how I should manage this blog if I'm going to keep at it. I'd like to know how you typically discover...
  • A World Without Competition
    Try to imagine what things would be like today had there not been fierce competition in certain key parts of our world.  I’ll give you some ...
  • Book Update
    I posted some gibberish a few weeks ago about another book project.  Well, I'm getting close to wrapping it up, so I thought I'd go ...
  • Cost
    Software technology, like any technology, provides a means to solving problems.  Some big. Some small.  Some that help.  Some that hurt.  An...
  • Windows 7: Default User vs All Users
    A lot of confusion seems to occur with understanding the difference between the "Default User" profile, and the "All Users...
  • Time to Give Props
    With the ever-expanding volume and breadth of information on the Internet today, it's easy to focus on my own thoughts, experiences, ide...
  • Table of Contents (Preliminary)
    Here's the preliminary Table of Contents for my new book "The AutoCAD Network Administrator's Bible - 2013 Edition".  I...
  • The Nicest IT and IT Vendor Folks I Know
    I've ranted many times before how it's unfair to "hate" an entire company, without providing a rationale for it based on s...
  • Windows 8
    Two small, yet irritating things, that I hope Windows 8 addresses with respect to Windows 7: Being able to put the Recycle Bin in the S...
  • Stupid Assumptions
    After years of watching sci-fi TV shows, movies, etc. it's finally come to a point where even the so-called brightest of our authors and...

Categories

  • a
  • activation
  • active directory
  • advertising
  • agile
  • agility
  • amazon
  • american
  • apple
  • application virtualization
  • applications
  • art
  • articles
  • asp
  • augi
  • authors
  • autocad
  • AutoCAD Autodesk
  • autodesk
  • autolisp
  • automation
  • automotive
  • backups
  • batch
  • beer
  • beta
  • blackberry
  • blogs
  • bongloads
  • book
  • books
  • Books writing kindle amazon technology business projects
  • browsers
  • business
  • cad
  • career
  • certification
  • chrome
  • city government
  • civilization
  • cloud services
  • cmd
  • cmmi
  • comedy
  • command
  • community
  • computers
  • conferences
  • config manager
  • consultants
  • consulting
  • contracting
  • cranium drainium
  • crapware
  • culture
  • data center
  • data mining
  • databases
  • deployment
  • directx
  • DLL
  • domains
  • dumb
  • earth
  • economy
  • editor
  • education
  • election
  • elections
  • employment
  • engineering
  • entertainment
  • environment
  • error monitoring
  • events
  • exchange
  • facebook
  • family
  • firefox
  • flexnet
  • fud
  • fun
  • funny
  • games
  • gary vaynerchuk
  • gmail
  • google
  • government
  • group policy
  • hampton roads
  • health
  • history
  • holidays
  • home
  • html5
  • humor
  • hyper-v
  • iis
  • industry
  • infrastructure
  • installation
  • installshield
  • internet
  • internet explorer
  • interviews
  • jobs
  • jtbworld
  • kindle
  • kixtart
  • lab setup
  • languages
  • ldap
  • learning
  • legal
  • licensing
  • life
  • lifecycle
  • linux
  • lisp
  • logging
  • management
  • manufacturing
  • marketing
  • markets
  • mdop
  • mdt
  • medical
  • messaging
  • microsoft
  • microsoft access
  • military
  • mountains
  • movies
  • mozilla
  • music
  • nature
  • network administration
  • news
  • nook
  • nothing
  • office
  • open source
  • openoffice
  • opera
  • operating systems
  • oracle
  • osx
  • packaging
  • patches
  • people
  • photos
  • podcasts
  • policy
  • politics
  • powershell
  • predictions
  • process automation
  • products
  • programming
  • projects
  • psychology
  • publishing
  • rail
  • reading
  • registry
  • religion
  • reporting
  • reviews
  • rsat
  • rss
  • safari
  • safety
  • sales
  • satire
  • sccm
  • scheduling
  • science
  • scripting
  • search
  • security
  • servers
  • services
  • sharepoint
  • shopping
  • sms
  • social stuff
  • society
  • softgrid
  • software assurance
  • software deployment
  • software development
  • software packaging
  • sony
  • speaking
  • sports
  • sql express
  • sql server
  • statistics
  • Statistics news marketing
  • steve jobs
  • stories
  • stuff
  • stupidity
  • symantec
  • sysinternals
  • system center
  • systems architecture
  • t-sql
  • taxes
  • technet
  • technical support
  • technology
  • TED
  • ted talks
  • testing
  • textpad
  • thoughts
  • traffic
  • training
  • transportation
  • travel
  • troubleshooting
  • tutorials
  • twitter
  • ubuntu
  • unattend
  • unemployment
  • updates
  • upfront ezine
  • utilities
  • vacation
  • vba
  • vbscript
  • video
  • virginia
  • virginia beach
  • virtualization
  • visual lisp
  • vmware
  • vmware server
  • voting
  • war
  • weather
  • web
  • web browsers
  • web development
  • web sites
  • windows
  • windows 7
  • windows live
  • windows server
  • windows server 2012
  • windows8
  • winpe
  • wise
  • wmi
  • work
  • writing
  • ws08
  • wsus
  • wwa
  • x64
  • xml
  • ze frank

Blog Archive

  • ►  2013 (37)
    • ►  October (1)
    • ►  September (5)
    • ►  August (8)
    • ►  July (2)
    • ►  June (4)
    • ►  May (4)
    • ►  April (2)
    • ►  March (2)
    • ►  February (8)
    • ►  January (1)
  • ▼  2012 (120)
    • ►  December (14)
    • ▼  November (12)
      • Pre-Announcement of a Pre-Announcements
      • Wrapping Infrastructure with Duct Tape, Glue and S...
      • Deploy Windows 8 Start Tiles Using Group Policy Pr...
      • It's Scripting Time Again! AD Server Descriptions
      • Thanksgiving Special: 7 Easy Computer Performance ...
      • Windows 8 / Server 2012 Shutdown Safety Tip
      • Why "Coming Soon" Can Be a Bad Idea
      • A Little Humor for Monday morning
      • Crude But Effective: Part 2, the Electric Boogaloo
      • Blog News and Updates!
      • Crude But Effective (ConfigMgr Right-Click Tools T...
      • Why I'm Still Not 100% on PowerShell
    • ►  October (10)
    • ►  September (7)
    • ►  August (3)
    • ►  July (2)
    • ►  June (6)
    • ►  May (6)
    • ►  April (20)
    • ►  March (16)
    • ►  February (18)
    • ►  January (6)
  • ►  2011 (343)
    • ►  December (15)
    • ►  November (23)
    • ►  October (27)
    • ►  September (35)
    • ►  August (29)
    • ►  July (17)
    • ►  June (23)
    • ►  May (20)
    • ►  April (38)
    • ►  March (61)
    • ►  February (54)
    • ►  January (1)
Powered by Blogger.

About Me

Unknown
View my complete profile