Tag Archives: Active Directory

(VBScript) Rename PCs Based on Serial Number and OU

This is a VBScript that will rename a PC into the format DI-SERIALNO (i.e. department initials followed by the serial number).  For this, you will need to setup an account in Active Directory that has rights to change atrributes on Computer objects.  The password for this account is stored in the script in plaintext.  What I did was set up a utility account that was a member of Domain Guests and nothing else, and on the parent OU for workstations, I gave that account Write all properties permission for Descendant Computer objects:

Once that is setup, you can run the following script on any workstation.  This has only been tested on Dell workstations, so I don’t know it will run on e.g. an HP workstation with regards to retrieving the serial number.

Set objSysInfo = CreateObject("ADSystemInfo")
strComputer = objSysInfo.ComputerName
Set objComputer = GetObject("LDAP://" & strComputer)
strOU = ""

If objComputer.Parent = "LDAP://OU=HR,OU=Workstations,DC=EXAMPLE,DC=COM" Then
	strOU = "HR"
ElseIf objComputer.Parent = "LDAP://OU=IT,OU=Workstations,DC=EXAMPLE,DC=COM" Then
	strOU = "IT"
ElseIf objComputer.Parent = "LDAP://OU=Finance,OU=Workstations,DC=EXAMPLE,DC=COM" Then
        strOU = "FI"
End If

If strOU = "" Then
End If

strSerialNumber = ""

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colSMBIOS = objWMIService.ExecQuery("Select * from Win32_SystemEnclosure")
For Each objSMBIOS in colSMBIOS
	strSerialNumber = objSMBIOS.SerialNumber

If strSerialNumber = "" Then
End If

strNewComputerName = ""
strNewComputerName = strOU & "-" & strSerialNumber

strComputerName = ""
Dim objNTInfo
Set objNTInfo = CreateObject("WinNTSystemInfo")
strComputerName = ucase(objNTInfo.ComputerName)

If strComputerName = "" Then
End If

If strComputerName = strNewComputerName Then
End If

set objWMILocator = CreateObject("WbemScripting.SWbemLocator")
objWMILocator.Security_.AuthenticationLevel = 6
set objWMIComputer = objWMILocator.ConnectServer(strComputerName, "root\cimv2")
set objWMIComputerSystem = objWMIComputer.Get("Win32_ComputerSystem.Name='" & strComputerName & "'")
rc = objWMIComputerSystem.Rename(strNewComputerName, "password", "ad_renaming_account@example.com")

You will have to modify the If statement near the top to reflect your Active Directory structure and the last line at the bottom to reflect the credentials of the utility account. There are sanity checks in place to ensure that it does not result in a blank name, a name with no department initials, or a name with no serial number.

I have tested this with scripting in Group Policy. I found it is best to run it as a shutdown script to help avoid any renaming issues.  I recommend using this method to rename workstations in bulk, but I would keep the utility account enabled for only as long as necessary.