VBSCRIPT: Move Computer to Desired OU, Rename to Naming Standard, and Reboot/Shutdown

Overview:

                The following VBScript is used in conjunction with user provided information to move the local computer Active Directory account to the desired Organizational Unit, rename the computer both locally and in Active Directory, and reboot/shutdown/log off the computer if desired.  The naming standard created by the script requires the user to input the first three characters of the computer name which corresponds to the department the computer is issued to.  It then appends the provided information with the chassis type and the serial number.  For example, a computer in the Shipping department may begin with the designator “SHP”, be a desktop personal computer, and have the serial number 8K5H4L1.  With the provided input of “Name=SHP”, the computer name would be “SHP-PC-8K5H4L1”.  This allows the user or tech to instantly know the department the computer is located in, the type of computer it is, and the serial number of the unit.  The computer may be required to be in the corresponding OU named “SHIPPING”.  With the knowledge of the company’s Active Directory structure, the user can provide the following information “OU=Computers,OU=SHIPPING” and the VBScript will place the computer in the desired Organizational Unit.  The VBScript can also accept reboot/shutdown/log off commands being “Forced” or not.  The addition of the user input “Reboot” or “Forced Reboot” would cause the VBScript to reboot or cause a forced reboot as commanded.  All of these are command line arguments passed to the script and can be provided in any order or not provided at all.  The script outputs the results of the requested actions to a TXT or CSV file as well as Error Codes if there is an error.  It also outputs the computer manufacturer, computer serial number, computer name, and Organizational Unit information if desired.  If no actions are presented to the script it will simply output the information file to the programmed destination.  This VBScript does NOT join the computer to the domain.  It is assumed that the computer has already been joined manually or automatically by another process or the unattend.xml file provided to the operating system upon initial imaging.  The script can be used as a KACE K2000 post-installation task or a K1000 scripting task.  Since the script uses provided domain user credentials hard coded within it, it can be run by any user, local or domain, which has administrator rights to the local computer.  It is recommended that the script be encrypted before putting it into production to protect the sensitive data of the hard coded user credentials.  Being that this script can be called from any command line, it has many applications.

 

Configuration:

Before you can run the script you must provide it with the following information:

  • Domain User account with Active Directory rights
  • Domain User account Password
  • Domain DNS Server Name

This information is provided to the script by the user in between the “START YOUR DATA” and “END YOUR DATA” section at the beginning of the script:

                '!-- START YOUR DATA --!
                strUser = "domain\user"
                strPassword = "P@$$w0rD"
                strServer = "AAA.BBB.COM"
                strAppendRootDSE = "Yes"
                strOutputFile = "C:\ComputerName.txt"
                strEnableOutput = "On"
                strFileHeader = "On"
                strShowOUInfo = "On"
                strForceRebootIfRename = "Off"
                strDebugMode = "Off"
                '!--- END YOUR DATA ---!

strUser – This is the user provided domain account that has rights to the Active Directory.  It is suggested that you provide the domain and the user as so: “exampledomain\username”.

strPassword – This is the password for the above provided domain user account.

strServer – This is the DNS name of your Domain server.

strAppendRootDSE – The script will discover your RootDSE automatically and therefore it can append it to the user provided Organizational Unit information.  Turn this feature “Off” if you would like to pass the RootDSE information along with the Organizational Unit manually in the command line.

strOutputFile – Provides the script with the location and file name of the output file.  If the provided filename has the extension “CSV” the script will output in a Comma Separated Value format.  If a file type other than CSV or TXT is provided the script will assume that the output file is text format and therefore the output is the same as a “.txt” file.

strEnableOutput – Enables or disables the output file.

strFileHeader – Places a header at the beginning of the output file.  In a CSV format the script will add a third column titled “Error” to the header information and separate the error codes in to this provided column.  In TXT format the error codes are placed in the second “column” following the word “Error” next to the corresponding requested action.

strShowOUInfo – Adds Organizational Unit information to the end of the output file.  If enabled, it will display the Current OU if no OU Move action is required.  If action is required, it will output the old OU as well as the new OU for auditing purposes.

strForceRebootIfRename – Executes a “Forced Reboot” if a computer rename has been requested and the rename was successful.  This is left “Off” by default as the user can provide the command line argument “Forced Reboot” if so desired.  You may enable this if necessary.

strDebugMode – This is provided for advanced troubleshooting, manipulation and/or configuration of the script.  If you desire to make your own customizations you can enable this for testing and the Rename, OU Move, and Reboot/Shutdown commands will NOT be performed.

 

Command Line Execution:

The script can handle the following arguments passed to it:

“Name=” – This is required to activate the Rename function of the script.  Follow “Name=” with your required naming standard.  For example, if you wanted the computer name to start with SLS to designate the “Sales Department” you would provide the script with “Name=SLS”.

“OU=BBB,OU=AAA” – This is required to activate the OU Move function of the script.  With “strAppendRootDSE” enabled you do not have to provide the “DC=” information.  For example, if you have an OU named “Computers” within the OU named “SALES” on your Domain Controller you would provide the script with “OU=Computers,OU=SALES”.  Remember that OU’s are placed right to left to correspond to the top to bottom look of your Active Directory from a GUI view.  If “strAppendRootDSE” is disabled you will have to provide the DC information as well.  For example, “OU=Computers,OU=SALES,DC=Domain,DC=Com”

“Reboot” – This is required to provide the script with the required Shutdown command if desired.  The options are as follows: "LOG OFF", "FORCED LOG OFF", "SHUTDOWN", "FORCED SHUTDOWN", "REBOOT", "FORCED REBOOT", "POWER OFF", or "FORCED POWER OFF".  The arguments do not require capitalization to be correctly interpreted by the script but must have spaces where shown.

All three of the acceptable arguments can be passed to the script or any combination of the three and in any order.  You may use two of the arguments, only one of the arguments, or none at all.

Command line examples:

To rename the computer to “RCV” for the Receiving Department, place it in the RECEIVE Organizational Unit, and force a reboot of the computer:

Cscript.exe computeraccount.vbs "Name=RCV" "OU=Computers,OU=RECEIVE" "Forced Reboot"

To rename the computer to “RCV” and force a reboot of the computer:

Cscript.exe computeraccount.vbs "Name=RCV" "Forced Reboot"

To only move the computer account to the desired Organizational Unit:

Cscript.exe "OU=Computers,OU=RECEIVE"

To simply shutdown the computer:

Cscript.exe computeraccount.vbs "Shutdown"

Remember – Command line arguments can by placed in any order:

Cscript.exe computeraccount.vbs "Name=RCV" "OU=Computers,OU=RECEIVE" "Forced Reboot"

Is the same as:

Cscript.exe computeraccount.vbs "OU=Computers,OU=RECEIVE" "Forced Reboot" "Name=RCV"

If you would only like the script to create the output file on the local computer:

Cscript.exe computeraccount.vbs

 

Additional Information:

                This script is designed to interpret the Manufacturer Name and provide additional chassis type configurations based on that Manufacture Name.  By default, a Laptop or Notebook computer will be given the designator of “LT”, but if the Manufacturer Name begins with “PAN” for “Panasonic Corporation” then it assumes that the unit is a Toughbook and gives it the designator “TB”.  If the Manufacturer Name begins with “MOT” for “Motion Computing” then it assumes the unit is a Tablet and once again gives the designator “TB”.  The default section of the chassis type begins at line 191 with the text: “'Start Default Manufacturer Section”.  The additional Manufacturer types are located in the Function “findChassisType” on line 613.  The Motion Computing section goes from lines 619 to 703 or from the text “'Start Motion Computing Section” to “'End Motion Computing Section”.  The Panasonic Corporation section goes from lines 704 to 788 or from the text “'Start Panasonic Corporation Section” to “'End Panasonic Corporation Section”.  Additional sections can be provided.  The script truncates the name to its first three characters, sets it to uppercase, and then interprets it.  To add another manufacturer, simply copy a section, paste it after another section, and make the appropriate changes.  For example, if the manufacturer was “Hewlett-Packard” you would add the appropriately named section with the identifier “HEW” in the line “If strComputerManufacturer = "HEW" Then”.  If you do not want Panasonic Corporation or Motion Computing computers to have the “TB” designator and are not familiar with VBScript, simply edit the file and using the replace function of your text editor replace “TB” with “LT”.  This has been tested and will not corrupt the script.

                This script can be reconfigured to your company’s naming standard.  The section titled “'<Compile New Computer Name using Chassis Type and BIOS Serial Number>” on line 275 is where the script compiles the final computer name.  There are additional examples of naming standards provided within the script itself in this section.  You could, if desired, ignore the “Name=” argument completely and have the first designator of your computer naming standard be the truncated manufacturer name if you configure the script to do so.

                NetBIOS computer names are restricted to fifteen (15) characters.  This script will truncate the computer name to fourteen (14) characters due to errors caused by some older NetBIOS calls.  It assumes that the first three characters of the computer name are the three (3) characters provided by the “Name=” argument and then adds the chassis type and last seven (7) characters of the serial number with dashes in between.  Note: The script does NOT truncate the information in the “Name=” argument to three (3) characters so that longer name designators can be used.  Some serial numbers are longer than seven characters, but the last seven are the most unique, so that is why the script only uses the last seven characters.  All of this can be adjusted by advanced users understanding VBScript.  If you would like the computer name to be fifteen characters, you can edit line 284 and change the “14” to a “15”.  DO NOT use the replace function of your text editor to replace “14” with “15” for it will corrupt the script.  Here is the line and the change for use in a replace function of your text editor:

Before:

strNewName = UCase(Left(strArgName & "-" & strChassis & "-" & strShortSerial,14))

After:

strNewName = UCase(Left(strArgName & "-" & strChassis & "-" & strShortSerial,15))

                When renaming the computer or moving the computer account to the desired Organizational Unit, errors may occur.  These errors will be provided in the output file.  Rename errors are presented in their decimal form, however, OU Move errors are presented in a HEX format.  This is to assist the user in troubleshooting their issue with the script.  Online, you will find that most Rename errors are presented in decimal format while Active Directory requests are presented in a HEX format.  The script does NOT provide error descriptions as in testing some were found to be erroneous, but searching online using the error number provided useful information.  Because there are so many errors that can be provided the time to hard code descriptions that would be useful to the user was not taken.  It is assumed that the script is being used by Information Technology Professionals that have the resources to resolve error numbers into their corresponding descriptions and correct any issues.  If you do not want the OU Move errors to be in HEX format you can edit line 362 like so:

Before:

strOUMoveError = Hex(Err.Number)

After:

strOUMoveError = Err.Number

                This script does NOT overwrite existing domain accounts.  Therefore, if the user is attempting to rename the computer to a name reserved by an existing domain account the script will return the Error 2224 in the rename section of the output file.  This was purposeful to keep users from accidentally overwriting the existing account and causing it to lose its trust relationship with the domain.

                When troubleshooting or using the script for the first time, be sure to enable debug mode by setting strDebugMode to “ON” in the “'<User Provided Domain Information, Credentials, and Preferred Settings>” section at the beginning of the script.  This will ensure that you do not make any unwanted changes to the computer or its domain account.  Using the script with no arguments will output an information file.  If the “CurrentOU=” is listed, you are connecting to your domain properly.

                Remember that the local computer account that initiates the script must have local administrator rights on the local computer and that this script is designed to run locally.  It will not, nor is it programmed to, make changes to remote computers on the network.

                When using this script as a Post-Installation Task on the Dell KACE K2000 please keep in mind that once the task has completed a Rename of the local computer that the cached environment variable %COMPUTERNAME% is no longer valid until the computer has performed a reboot.  If you have additional tasks after this one that install software dependent upon the %COMPUTERNAME% environment variable then they will not function correctly.

                For security reasons, it is recommended that this script be encrypted before being put into production.  It is recommended that the user use ScrEnc.exe for encryption of this script.  When encrypting, be sure to rename the script from “.vbs” to “.vbe” or it will not function.

                There are ample remark statements throughout the script to assist you in the understanding and the manipulation of the script to suit your needs.  Users that understand VBScript can fully customize this script to their desires or the requirements of their employer.  Users that do NOT fully understand VBScript may be able to use these remarks to understand this VBScript and should have success making minor adjustments or changes to the script.  Users with NO confidence in editing VBScript should only make changes to the “'<User Provided Domain Information, Credentials, and Preferred Settings>” section as it was designed to provide simple configuration by the most basic user.  Please review the entire script for all remarks for any additional configuration options not listed in this text.

 

The Script – computeraccount.vbs:

'*Current File Name - "computeraccount.vbs" or "computeraccount.vbe" (If Encrypted)
'*VBScript to move local computer AD account to desired OU,
'    as well as rename the computer locally and on the domain.
'*(Default) vs (Optional):
'    Only one of the lines in this section is allowed to be operational therefore Remark the rest.
'*(Adjustable):
'    Edits can be made but make changes at Your Own Risk!
'*User customizations must be made in the START YOUR DATA to END YOUR DATA section below!
'*Advanced Users will find that this script is easy to customize to your specific needs.
'*Valid Power Commands:
'    "LOG OFF" "FORCED LOG OFF" "SHUTDOWN" "FORCED SHUTDOWN" "REBOOT" "FORCED REBOOT" "POWER OFF" "FORCED POWER OFF"
'*Command Line Usage Format:
'    cscript.exe computeraccount.vbe "NAME=(First 3 Characters of New Computer Name)" "(New Organizational Unit with Commas)" "(Reboot/Shutdown/Power Off)"
'*Command Line Usage Format Example:
'    cscript.exe computeraccount.vbe "NAME=AAA" "OU=OUNAME3,OU=OUNAME2,OU=OUNAME1" "REBOOT"

'<User Provided Domain Information, Credentials, and Preferred Settings>
'!-- START YOUR DATA --!
strUser = "domain\user"                ' "domain\username" - (Domain Account with AD Rights.)
strPassword = "P@$$w0rD"             ' "P@$$w0rD" - (Password for above Domain Account.)
strServer = "AAA.BBB.COM"             ' "AAA.BBB.COM" OR "AAA.BBB.LOCAL" (The DNS Name of your Domain Server.)
strAppendRootDSE = "Yes"            ' "Yes" OR "No" - (Appends your RootDSE to the Destination OU Argument.)
strOutputFile = "C:\ComputerName.txt"         ' "C:\filename.txt" OR "C:\filename.csv" - (Output file Location, Name, and File Type.)
strEnableOutput = "On"                ' "On" OR "Off" - ("On" Enables output the the Output File. "Off" Disables output the the Output File.)
strFileHeader = "On"                 ' "On" OR "Off" - (Places a header at the beginning of the Output file)
strShowOUInfo = "On"                ' "On" OR "Off" - (Places OU information in the Output File. You may want this hidden.)
strForceRebootIfRename = "Off"            ' "On" OR "Off" - (If the rename is successful: "On" = Execute "Forced Reboot" | "Off" = Executes User Shutdown Command if Provided.)
strDebugMode = "Off"                ' "On" OR "Off" - (If "On" then this script will NOT perform any critical actions like Rename, Moving to OU, or Any Shutdown Command.)
'!--- END YOUR DATA ---!

'<Global Settings, Attributes, and Variables>
Const HKEY_LOCAL_MACHINE = &H80000002
Const ADS_SECURE_AUTHENTICATION = &H1
Const ADS_SERVER_BIND = &H200
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objArg = WScript.Arguments
Set objNS = GetObject("LDAP:")
Set objRootDSE = objNS.OpenDSObject("LDAP://" & strServer & "/RootDSE", strUser, strPassword, ADS_SERVER_BIND Or ADS_SECURE_AUTHENTICATION)
strDNSDomain = objRootDSE.Get("defaultNamingContext")
strAppendRootDSE=UCase(strAppendRootDSE)
strEnableOutput=UCase(strEnableOutput)
strFileHeader=UCase(strFileHeader)
strShowOUInfo=UCase(strShowOUInfo)
strForceRebootIfRename=UCase(strForceRebootIfRename)
strDebugMode=UCase(strDebugMode)
strRenameSuccess = 0
strOUMoveSuccess = 0

'<Error Checking of Arguments>
On Error Resume Next
strArg0 = objArg(0)
If Err.Number <> 0 Then
    strArg0 = "NA"
    Err.Clear
End If
strArg1 = objArg(1)
If Err.Number <> 0 Then
    strArg1 = "NA"
    Err.Clear
End If
strArg2 = objArg(2)
If Err.Number <> 0 Then
    strArg2 = "NA"
    Err.Clear
End If
On Error Goto 0

'<Assessing what information types have been passed through Arguments to the Script>
strArgName = "NA"
strArgOU = "NA"
strArgReboot = "NA"
If strArg0 <> "NA" Then
    If strArg1 <> "NA" Then
        If strArg2 <> "NA" Then
            If argumentFuntion(strArg0) = "OU" Then strArgOU = strArg0
            If argumentFuntion(strArg0) = "Name" Then strArgName = strArg0
            If argumentFuntion(strArg0) = "ShutdownCommand" Then strArgReboot = strArg0
            If argumentFuntion(strArg1) = "OU" Then strArgOU = strArg1
            If argumentFuntion(strArg1) = "Name" Then strArgName = strArg1
            If argumentFuntion(strArg1) = "ShutdownCommand" Then strArgReboot = strArg1
            If argumentFuntion(strArg2) = "OU" Then strArgOU = strArg2
            If argumentFuntion(strArg2) = "Name" Then strArgName = strArg2
            If argumentFuntion(strArg2) = "ShutdownCommand" Then strArgReboot = strArg2
        Else
            If argumentFuntion(strArg0) = "OU" Then strArgOU = strArg0
            If argumentFuntion(strArg0) = "Name" Then strArgName = strArg0
            If argumentFuntion(strArg0) = "ShutdownCommand" Then strArgReboot = strArg0
            If argumentFuntion(strArg1) = "OU" Then strArgOU = strArg1
            If argumentFuntion(strArg1) = "Name" Then strArgName = strArg1
            If argumentFuntion(strArg1) = "ShutdownCommand" Then strArgReboot = strArg1    
        End If
    Else
        If argumentFuntion(strArg0) = "OU" Then strArgOU = strArg0
        If argumentFuntion(strArg0) = "Name" Then strArgName = strArg0
        If argumentFuntion(strArg0) = "ShutdownCommand" Then strArgReboot = strArg0
    End If
End If
'Remove Spaces and "Name=" From the New Name Designator and Capitalize it:
strArgName = Replace((Replace((UCase(strArgName))," ","")),"NAME=","")

'<Create New Output File for Script Logs and Configure File Type>
If strEnableOutput = "ON" Then
    strFileType = Right(strOutputFile,3)
    'Check to see if the File is open in Excel or Word and if so Close it:
    On Error Resume Next
    Set localApp = GetObject(strOutputFile).Application
    If Err Then
        'Excel and/or Word is not running. Continue Script.
    Else
        localApp.ActiveDocument.Save
        If localApp.ActiveDocument.Close <> 0 Then
            For Each objWorkbook In localApp.Workbooks
                If objWorkbook.FullName = strOutputFile Then
                    objWorkbook.Saved = True
                    objWorkbook.Close
                End If
            Next
        End If
    End If
    Set objFile = objFSO.CreateTextFile(strOutputFile,True)
    'Write to Output File Header Information if strFileHeader = "ON": (Optional)
    If strFileHeader = "ON" Then
        If UCase(strFileType) = "CSV" Then
            'Set CSV Header to "Attribute,Value,Error": (Optional)
            objFile.Write "Attribute,Value,Error" & vbCrLf
        Else
            'Set TXT or Other format header to "  Attribute  |     Value      |     Error" (Optional)
            objFile.Write "  Attribute  |     Value" & vbCrLf
        End If
    Else
        'User did not set strFileHeader = "ON" in the <User Provided Domain Information, Credentials, and Preferred Settings> Section Above.
    End If
End If

'<Determine Current Computer Name in Operating System>
Set wshShell = WScript.CreateObject("WScript.Shell")
strComputerName = wshShell.ExpandEnvironmentStrings("%COMPUTERNAME%")

'<Determine Computer Manufacturer in Operating System>
Set colManufacturer = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
For each objManufacturer in colManufacturer
    'Sets a Full Manufacturer String Variable for Mandatory and Optional Use in this Script:
    strFullManufacturer = objManufacturer.Manufacturer
    'Write to Output File "Manufacturer = ":
    If strEnableOutput = "ON" Then
        If UCase(strFileType) = "CSV" Then
            objFile.Write "Manufacturer," & strFullManufacturer & vbCrLf
        Else
            objFile.Write "Manufacturer = " & strFullManufacturer & vbCrLf
        End If
    End If
    'Selects only the FIRST 3 characters of the Manufacturer for a Optional Short version of the Variable: (Adjustable)
    strShortManufacturer = Left(objManufacturer.Manufacturer,3)
    'Sets a Full Model String Variable for Mandatory and Optional Use in this Script:
    strModel = objManufacturer.Model
    'Write to Output File "Model        = ":
    If strEnableOutput = "ON" Then
        If UCase(strFileType) = "CSV" Then
            objFile.Write "Model," & strModel & vbCrLf
        Else
            objFile.Write "Model        = " & strModel & vbCrLf
        End If
    End If
Next

'<Determine Serial Number in the BIOS>
Set colBIOS = objWMIService.ExecQuery("Select * from Win32_BIOS")
For each objBIOS in colBIOS
    strSerial = objBIOS.SerialNumber
    'Write to Output File "Serial       = ":
    If strEnableOutput = "ON" Then
        If UCase(strFileType) = "CSV" Then
            objFile.Write "Serial," & strSerial & vbCrLf
        Else
            objFile.Write "Serial       = " & strSerial & vbCrLf
        End If
    End If
    'Selects only the LAST 8 characters of the Serial Number for a Mandatory Short version of the Variable: (Adjustable)
    strShortSerial = Right(objBIOS.SerialNumber,7)
    'Sets a Full Serial String Variable for Mandatory and Optional Use in this Script:
    strFullSerial = objBIOS.SerialNumber
Next

'<Determine Computer Chassis Type>
'You can customize the Chassis Designations in each "case" here: (Adjustable)
Set colChassis = objWMIService.ExecQuery("Select * from Win32_SystemEnclosure")
strChassis = findChassisType(strFullManufacturer)
If strChassis = "" Then
    'Start Default Manufacturer Section
    For Each objChassis in colChassis
        For  Each strChassisType in objChassis.ChassisTypes
            Select Case strChassisType
                Case 1
                    'Other
                    strChassis =  "PC"
                Case 2
                    'Unknown
                    strChassis =  "PC"
                Case 3
                    'Desktop
                    strChassis =  "PC"
                Case 4
                    'Low Profile Desktop
                    strChassis =  "PC"
                Case 5
                    'Pizza Box
                    strChassis =  "PC"
                Case 6
                    'Mini Tower
                    strChassis =  "PC"
                Case 7
                    'Tower
                    strChassis =  "PC"
                Case 8
                    'Portable
                    strChassis =  "LT"
                Case 9
                    'Laptop
                    strChassis =  "LT"
                Case 10
                    'Notebook
                    strChassis =  "LT"
                Case 11
                    'Hand Held
                    strChassis =  "LT"
                Case 12
                    'Docking Station
                    strChassis =  "PC"
                Case 13
                    'All in One
                    strChassis =  "PC"
                Case 14
                    'Sub Notebook
                    strChassis =  "LT"
                Case 15
                    'Space-Saving
                    strChassis =  "PC"
                Case 16
                    'Lunch Box
                    strChassis =  "PC"
                Case 17
                    'Main System Chassis
                    strChassis =  "PC"
                Case 18
                    'Expansion Chassis
                    strChassis =  "PC"
                Case 19
                    'Sub Chassis
                    strChassis =  "PC"
                Case 20
                    'Bus Expansion Chassis
                    strChassis =  "PC"
                Case 21
                    'Peripheral Chassis
                    strChassis =  "PC"
                Case 22
                    'Storage Chassis
                    strChassis =  "PC"
                Case 23
                    'Rack Mount Chassis
                    strChassis =  "PC"
                Case 24
                    'Sealed-Case PC
                    strChassis =  "PC"
                Case Else
                    strChassis =  "PC"
            End Select
        Next
    Next
    'End Default Manufacturer Section
End If

'<Compile New Computer Name using Chassis Type and BIOS Serial Number>
'This is where the Final Format of the New Computer Name comes together.
'You can make edits to this section to suit your needs.
'Create your own Company Custom Naming Standard!
'Remember: Computer Names can only be 15 Characters long!
'This will truncate the name and capitalize it: UCase(Left(YOUR-NAMING-STANDARD,15))
'Some Optional examples are provided along with the Default:

'"Name=" Argument - Chassis Type - Serial Number as the New Computer Name with no spaces in between: (Default)
strNewName = UCase(Left(strArgName & "-" & strChassis & "-" & strShortSerial,14))

'Manufacturer Short Name - Chassis Type - Serial Number as the New Computer Name with no spaces in between: (Optional)
'strNewName = UCase(Left(strShortManufacturer & "-" & strChassis & "-" & strShortSerial,15))

'Hard coded Information  - Chassis Type - Serial Number as the New Computer Name with no spaces in between: (Optional)
'strNewName = UCase(Left("AAA" & "-" & strChassis & "-" & strShortSerial,15))

'<Document Current Computer Name and Future Computer Name>
If strArgName <> "NA" Then
    If strEnableOutput = "ON" Then
        'Write to Output File "OldName      = ":
        If UCase(strFileType) = "CSV" Then
            objFile.Write "OldName," & strComputerName & vbCrLf
        Else
            objFile.Write "OldName      = " & strComputerName & vbCrLf
        End If
        'Write to Output File "NewName      = ":
        If UCase(strFileType) = "CSV" Then
            objFile.Write "NewName," & strNewName & vbCrLf
        Else
            objFile.Write "NewName      = " & strNewName & vbCrLf
        End If
    End If
Else
    'User did not provide the "Name=" Argument which is the First Designator in the New Computer Name!
    'Write to Output File "ComputerName = ":
    If strEnableOutput = "ON" Then
        If UCase(strFileType) = "CSV" Then
            objFile.Write "ComputerName," & strComputerName & vbCrLf
        Else
            objFile.Write "ComputerName = " & strComputerName & vbCrLf
        End If
    End If
End If

'<Move Local Computer AD Account to Desired OU>
If strArgOU = "NA" Then
    'Write to Output File "OUMove       = Not Applicable":
    If strEnableOutput = "ON" Then
        If UCase(strFileType) = "CSV" Then
            'Remove the remark from this line to show OUMove status in Output File if it was not activated:
            'objFile.Write "OUMove,Not Applicable" & vbCrLf
            strOUMoveSuccess = 0
        Else
            'Remove the remark from this line to show OUMove status in Output File if it was not activated:        
            'objFile.Write "OUMove       = Not Applicable" & vbCrLf
            strOUMoveSuccess = 0
        End If
    End If
Else
    'Compile Full Active Directory Path for the New Organizational Unit
    If strAppendRootDSE = "YES" Then
        'Appends the RootDSE/Forest to the End of the OU provided in the Second Argument:
        strADsPath = strArgOU & "," & strDNSDomain
    Else
        'Assumes the Second Argument provided is the Full OU path:
        strADsPath = strArgOU
    End If
    Set objADContainer = objNS.OpenDSObject("LDAP://" & strServer & "/" & strADsPath, strUser, strPassword, ADS_SERVER_BIND Or ADS_SECURE_AUTHENTICATION)  
    strCurrentAdPath = isComputerAccountAdsPath(strComputerName)
    'Checks if the Computer account is already in the correct OU before proceeding:
    If ( InStr(UCase(isComputerAccountAdsPath(strComputerName)),UCase(strADsPath)) ) Then
        'Write to Output File "OUMove       = Not Required":
        If strEnableOutput = "ON" Then
            If UCase(strFileType) = "CSV" Then
                objFile.Write "OUMove,Not Required" & vbCrLf
                strOUMoveSuccess = 1
            Else
                objFile.Write "OUMove       = Not Required" & vbCrLf
                strOUMoveSuccess = 1
            End If
        End If
    Else
        If strDebugMode <> "ON" then
            'OU Move Command:
            On Error Resume Next
            Return = objADContainer.MoveHere("LDAP://" & strServer & "/" & strCurrentAdPath, vbNullString)
            strOUMoveError = Hex(Err.Number)
            On Error Goto 0
        End If
        'Confirm Move:
        If ( InStr(UCase(isComputerAccountAdsPath(strComputerName)),UCase(strADsPath)) ) Then
            'Write to Output File "OUMove       = Success":
            If strEnableOutput = "ON" Then
                If UCase(strFileType) = "CSV" Then
                    objFile.Write "OUMove,Success" & vbCrLf
                    strNewAdsPath = isComputerAccountAdsPath(strComputerName)
                    strOUMoveSuccess = 1
                Else
                    objFile.Write "OUMove       = Success" & vbCrLf
                    strNewAdsPath = isComputerAccountAdsPath(strComputerName)
                    strOUMoveSuccess = 1
                End If
            End If
        Else
            'Write to Output File "OUMove       = Failure":
            If strEnableOutput = "ON" Then
                If UCase(strFileType) = "CSV" Then
                    objFile.Write "OUMove,Failure," & Chr(34) & strOUMoveError & Chr(34) & vbCrLf
                    strOUMoveSuccess = 0
                Else
                    objFile.Write "OUMove       = Error " & strOUMoveError & vbCrLf
                    strOUMoveSuccess = 0
                End If
            End If
        End If
    End If
End If

'<Rename Computer both Locally and in Active Directory>
If strArgName = "NA" Then
    'Write to Output File "Rename = Not Applicable":
    If strEnableOutput = "ON" Then
        If UCase(strFileType) = "CSV" Then
            'Remove the remark from this line to show Rename status in Output File if it was not activated:        
            'objFile.Write "Rename,Not Applicable" & vbCrLf
            strRenameSuccess = 0
        Else
            'Remove the remark from this line to show Rename status in Output File if it was not activated:            
            'objFile.Write "Rename       = Not Applicable" & vbCrLf
            strRenameSuccess = 0
        End If
    End If
Else
    If (strArgOU <> "NA") And (strOUMoveSuccess = 0)Then
        'Write to Output File "Rename       = OUMove Required":
        If strEnableOutput = "ON" Then
            If UCase(strFileType) = "CSV" Then
                objFile.Write "Rename,OUMove Required" & vbCrLf
                strRenameSuccess = 0
            Else
                objFile.Write "Rename       = OUMove Required" & vbCrLf
                strRenameSuccess = 0
            End If
        End If
    Else
        'Checks if the Current Computer Name does not match the New Computer Name before proceeding:
        If strComputerName <> strNewName Then
            For Each objComputer in objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
                'Rename Command:
                On Error Resume Next
                If strDebugMode <> "ON" then Return = objComputer.rename(strNewName,strPassword,strUser)
                strRenameError = Err.Number
                On Error Goto 0
                'Confirm Rename:
                objRegistry.GetStringValue HKEY_LOCAL_MACHINE, "SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName", "ComputerName", strNameCheck
                If (Return = 0) And (UCAse(strNameCheck) = UCase(strNewName)) Then
                    'Write to Output File "Rename       = Success":
                    If strEnableOutput = "ON" Then
                        If UCase(strFileType) = "CSV" Then
                            objFile.Write "Rename,Success" & vbCrLf
                            strRenameSuccess = 1
                        Else
                            objFile.Write "Rename       = Success" & vbCrLf
                            strRenameSuccess = 1
                        End If
                    End If
                Else
                    'Write to Output File "Rename       = Failure        = Error ":
                    If strEnableOutput = "ON" Then
                        If UCase(strFileType) = "CSV" Then
                            objFile.Write "Rename,Failure," & Chr(34) & Return & Chr(34) & vbCrLf
                            strRenameSuccess = 0
                        Else
                            objFile.Write "Rename       = Error " & Return & vbCrLf
                            strRenameSuccess = 0
                        End If
                    End If
                End If
            Next
        Else
            'Write to Output File "Rename       = Not Required":
            If strEnableOutput = "ON" Then
                If UCase(strFileType) = "CSV" Then
                    objFile.Write "Rename,Not Required" & vbCrLf
                    strRenameSuccess = 0
                Else
                    objFile.Write "Rename       = Not Required" & vbCrLf
                    strRenameSuccess = 0
                End If
            End If
        End If
    End If
End If

'<Close Output File for Script Logs>
If strEnableOutput = "ON" Then
    If (strShowOUInfo = "ON") And (strOUMoveSuccess = 0) Then
        'Write to Output File "CurrentOU    = ":
        If isComputerAccountAdsPath(strComputerName) <> "" Then
            If UCase(strFileType) = "CSV" Then
                objFile.Write "CurrentOU," & Chr(34) & isComputerAccountAdsPath(strComputerName) & Chr(34) & vbCrLf
            Else
                objFile.Write "CurrentOU    = " & isComputerAccountAdsPath(strComputerName) & vbCrLf
            End If
        Else
            If strRenameSuccess = 1 Then
                If UCase(strFileType) = "CSV" Then
                    objFile.Write "CurrentOU," & Chr(34) & Replace(isComputerAccountAdsPath(strNewName),strComputerName,strNewName) & Chr(34) & vbCrLf
                Else
                    objFile.Write "CurrentOU    = " & Replace(isComputerAccountAdsPath(strNewName),strComputerName,strNewName) & vbCrLf
                End If
            End If
        End If
    End If
    If (strShowOUInfo = "ON") And (strOUMoveSuccess = 1) Then
        'Write to Output File "OldOU        = ":
        If UCase(strFileType) = "CSV" Then
            objFile.Write "OldOU," & Chr(34) & strCurrentAdPath & Chr(34) & vbCrLf
        Else
            objFile.Write "OldOU        = " & strCurrentAdPath & vbCrLf
        End If
        'Write to Output File "NewOU        = ":
        If (isComputerAccountAdsPath(strComputerName) = "") And (strRenameSuccess = 1) Then
            If UCase(strFileType) = "CSV" Then
                objFile.Write "NewOU," & Chr(34) & Replace(strNewAdsPath,strComputerName,strNewName) & Chr(34) & vbCrLf
                'objFile.Write "NewOU,Requires Reboot" & vbCrLf
            Else
                objFile.Write "NewOU        = " & Replace(strNewAdsPath,strComputerName,strNewName) & vbCrLf
                'objFile.Write "NewOU        = Requires Reboot" & vbCrLf
            End If        
        Else
            If strRenameSuccess = 1 Then
                If UCase(strFileType) = "CSV" Then
                    objFile.Write "NewOU," & Chr(34) & Replace(isComputerAccountAdsPath(strComputerName),strComputerName,strNewName) & Chr(34) & vbCrLf
                Else
                    objFile.Write "NewOU        = " & Replace(isComputerAccountAdsPath(strComputerName),strComputerName,strNewName) & vbCrLf
                End If
            Else
                If UCase(strFileType) = "CSV" Then
                    objFile.Write "NewOU," & Chr(34) & isComputerAccountAdsPath(strComputerName) & Chr(34) & vbCrLf
                Else
                    objFile.Write "NewOU        = " & isComputerAccountAdsPath(strComputerName) & vbCrLf
                End If
            End If
        End If
    End If
objFile.Close
End If

'<Reboot/Shutdown/Power Off/Log Off Computer>
'Activate this by sending the Argument "Reboot" or "Shutdown" to the Script or by setting strForceRebootIfRename = "ON":
Set objWMIShutdown = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!\\.\root\cimv2")
Set colOperatingSystems = objWMIShutdown.ExecQuery("Select * from Win32_OperatingSystem")
'If strForceRebootIfRename = "ON" and Rename was Successful, this will Force a Reboot:
If (strForceRebootIfRename = "ON") And (strRenameSuccess = 1) Then
    'Forced Reboot
    If strDebugMode <> "ON" then
        For Each objOperatingSystem in colOperatingSystems
            objOperatingSystem.Win32Shutdown(2 + 4)
        Next
    End If
Else
    'If strForceRebootIfRename = "OFF" and the User provided a Shutdown Command, this will Execute the command:
    If strDebugMode <> "ON" then
        For Each objOperatingSystem in colOperatingSystems
            'Log Off
            If UCase(strArgReboot) = "LOG OFF" Then objOperatingSystem.Win32Shutdown(0)
            'Forced Log Off
            If UCase(strArgReboot) = "FORCED LOG OFF" Then objOperatingSystem.Win32Shutdown(0 + 4)
            'Shutdown
            If UCase(strArgReboot) = "SHUTDOWN" Then objOperatingSystem.Win32Shutdown(1)
            'Forced Shutdown
            If UCase(strArgReboot) = "FORCED SHUTDOWN" Then objOperatingSystem.Win32Shutdown(1 + 4)
            'Reboot
            If UCase(strArgReboot) = "REBOOT" Then objOperatingSystem.Win32Shutdown(2)
            'Forced Reboot
            If UCase(strArgReboot) = "FORCED REBOOT" Then objOperatingSystem.Win32Shutdown(2 + 4)
            'Power Off
            If UCase(strArgReboot) = "POWER OFF" Then objOperatingSystem.Win32Shutdown(8)
            'Forced Power Off
            If UCase(strArgReboot) = "FORCED POWER OFF" Then objOperatingSystem.Win32Shutdown(8 + 4)
        Next
    End If
End If

'<Quit This Script!>
WScript.Quit

'<Function to Confirm the AD Path of the Local Computer Account>
Function isComputerAccountAdsPath(host)  
    Set adoCommand = CreateObject("ADODB.Command")
    Set adoConnection = CreateObject("ADODB.Connection")
    adoConnection.Provider = "ADsDSOObject"
    adoConnection.Properties("User ID") = strUser
    adoConnection.Properties("Password") = strPassword
    adoConnection.Properties("Encrypt Password") = True
    adoConnection.Properties("ADSI Flag") = ADS_SERVER_BIND Or ADS_SECURE_AUTHENTICATION
    adoConnection.Open "Active Directory Provider"
    Set adoCommand.ActiveConnection = adoConnection
    adoCommand.CommandText = "<LDAP://" & strServer & "/" & strDNSDomain & ">;(&(objectCategory=computer)(objectClass=computer)(name=" & host & "));distinguishedName;subtree"
    adoCommand.Properties("Page Size") = 100
    adoCommand.Properties("Timeout") = 30
    adoCommand.Properties("Cache Results") = False
    Set adoRecordset = adoCommand.Execute
    Do Until adoRecordset.EOF
        If adoRecordset.recordcount = 0 Then  
            isComputerAccountAdsPath = ""
        Else  
            isComputerAccountAdsPath = cstr(adoRecordset.Fields("distinguishedName").Value)
        End If
        adoRecordset.MoveNext
    Loop
adoRecordset.Close
adoConnection.Close
End Function  

'<Function to Determine Provided Argument Type>
Function argumentFuntion(argType)
    If UCase(Instr(argType,",")) <> 0 Then
        argumentType = "OU"
    Else
        If UCase(argType) = "LOG OFF" Then argumentType = "ShutdownCommand"
        If UCase(argType) = "FORCED LOG OFF" Then argumentType = "ShutdownCommand"
        If UCase(argType) = "SHUTDOWN" Then argumentType = "ShutdownCommand"
        If UCase(argType) = "FORCED SHUTDOWN" Then argumentType = "ShutdownCommand"
        If UCase(argType) = "REBOOT" Then argumentType = "ShutdownCommand"
        If UCase(argType) = "FORCED REBOOT" Then argumentType = "ShutdownCommand"
        If UCase(argType) = "POWER OFF" Then argumentType = "ShutdownCommand"
        If UCase(argType) = "FORCED POWER OFF" Then argumentType = "ShutdownCommand"        
    End If
    If (argumentType = "OU") Or (argumentType = "ShutdownCommand") Then
        argumentFuntion = argumentType
    Else
        If UCase(Left(argType,5)) = "NAME=" Then argumentFuntion = "Name"
    End If
End Function

'<Function to Determine Chassis Type Based on Manufacturer>
'This Function allows for Alternate Chassis Designations Based on the Manufacturer.
'You can copy an existing section, paste it in as a new section, and then edit it accordingly.
Function findChassisType(strComputerManufacturer)
    Set colChassis = objWMIService.ExecQuery("Select * from Win32_SystemEnclosure")
    strComputerManufacturer = Left((Replace((UCase(strComputerManufacturer))," ","")),3)
    'Start Motion Computing Section
    If strComputerManufacturer = "MOT" Then
    For Each objChassis in colChassis
        For Each strChassisType in objChassis.ChassisTypes
            Select Case strChassisType
                Case 1
                    'Other
                    strChassis =  "PC"
                Case 2
                    'Unknown
                    strChassis =  "PC"
                Case 3
                    'Desktop
                    strChassis =  "PC"
                Case 4
                    'Low Profile Desktop
                    strChassis =  "PC"
                Case 5
                    'Pizza Box
                    strChassis =  "PC"
                Case 6
                    'Mini Tower
                    strChassis =  "PC"
                Case 7
                    'Tower
                    strChassis =  "PC"
                Case 8
                    'Portable
                    strChassis =  "TB"
                Case 9
                    'Laptop
                    strChassis =  "TB"
                Case 10
                    'Notebook
                    strChassis =  "TB"
                Case 11
                    'Hand Held
                    strChassis =  "TB"
                Case 12
                    'Docking Station
                    strChassis =  "PC"
                Case 13
                    'All in One
                    strChassis =  "PC"
                Case 14
                    'Sub Notebook
                    strChassis =  "TB"
                Case 15
                    'Space-Saving
                    strChassis =  "PC"
                Case 16
                    'Lunch Box
                    strChassis =  "PC"
                Case 17
                    'Main System Chassis
                    strChassis =  "PC"
                Case 18
                    'Expansion Chassis
                    strChassis =  "PC"
                Case 19
                    'Sub Chassis
                    strChassis =  "PC"
                Case 20
                    'Bus Expansion Chassis
                    strChassis =  "PC"
                Case 21
                    'Peripheral Chassis
                    strChassis =  "PC"
                Case 22
                    'Storage Chassis
                    strChassis =  "PC"
                Case 23
                    'Rack Mount Chassis
                    strChassis =  "PC"
                Case 24
                    'Sealed-Case PC
                    strChassis =  "PC"
                Case Else
                    strChassis =  "PC"
            End Select
        Next
    Next
    findChassisType = strChassis
    End If
    'End Motion Computing Section
    'Start Panasonic Corporation Section
    If strComputerManufacturer = "PAN" Then
    For Each objChassis in colChassis
        For Each strChassisType in objChassis.ChassisTypes
            Select Case strChassisType
                Case 1
                    'Other
                    strChassis =  "PC"
                Case 2
                    'Unknown
                    strChassis =  "PC"
                Case 3
                    'Desktop
                    strChassis =  "PC"
                Case 4
                    'Low Profile Desktop
                    strChassis =  "PC"
                Case 5
                    'Pizza Box
                    strChassis =  "PC"
                Case 6
                    'Mini Tower
                    strChassis =  "PC"
                Case 7
                    'Tower
                    strChassis =  "PC"
                Case 8
                    'Portable
                    strChassis =  "TB"
                Case 9
                    'Laptop
                    strChassis =  "TB"
                Case 10
                    'Notebook
                    strChassis =  "TB"
                Case 11
                    'Hand Held
                    strChassis =  "TB"
                Case 12
                    'Docking Station
                    strChassis =  "PC"
                Case 13
                    'All in One
                    strChassis =  "PC"
                Case 14
                    'Sub Notebook
                    strChassis =  "TB"
                Case 15
                    'Space-Saving
                    strChassis =  "PC"
                Case 16
                    'Lunch Box
                    strChassis =  "PC"
                Case 17
                    'Main System Chassis
                    strChassis =  "PC"
                Case 18
                    'Expansion Chassis
                    strChassis =  "PC"
                Case 19
                    'Sub Chassis
                    strChassis =  "PC"
                Case 20
                    'Bus Expansion Chassis
                    strChassis =  "PC"
                Case 21
                    'Peripheral Chassis
                    strChassis =  "PC"
                Case 22
                    'Storage Chassis
                    strChassis =  "PC"
                Case 23
                    'Rack Mount Chassis
                    strChassis =  "PC"
                Case 24
                    'Sealed-Case PC
                    strChassis =  "PC"
                Case Else
                    strChassis =  "PC"
            End Select
        Next
    Next
    findChassisType = strChassis
    End If
    'End Panasonic Corporation Section
End Function

'Veritas Amor Pax


Sources:

VB Script to move a computer account to a specific OU according to the Computer name when joined to domain

Using AD MoveHere method with alternate credentials

Secure LDAP object manipulation with VBscript using alternate credentials

How Can I Use Alternate Credentials When Searching Active Directory?

Active Directory Computer Account Scripts - Rename a Computer and Computer Account

How Can I Determine if a Computer is a Laptop or a Desktop Machine?

Identifying the Chassis Type of a Computer

Computer Hardware Scripts - Retrieving BIOS Information

VBScript — Using error handling

 

Additional Links:

Notepad++ For editing this script

ScrEnc.exe For encrypting this script

 

Veritas Amor Pax