Tuesday, March 20, 2012

The best way to disable 4300 computer accounts in Active driectory

Reposting here for my own reference.
Original thread can be found here

Here is a VBScript program Richard Mueller wrote a few years ago to disable computer accounts from a text file. The file name and path are hard coded in the program, so the file can be anywhere. The file must be a list of computer names (NetBIOS names), one name per line:

--- Begin script ---
Option Explicit

Dim strFile, objFSO, objFile
Dim objRootDSE, strDNSDomain, objTrans, strNetBIOSDomain
Dim strComputer, strComputerDN, objComputer

' Constants for the NameTranslate object.
Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4 = 3
Const ADS_NAME_TYPE_1779 = 1

' Specify text file of computer NetBIOS names.
strFile = "c:\Scripts\Computers.txt"

' Open the file for read access.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFile, 1)

' Determine DNS name of domain from RootDSE.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")

' Use the NameTranslate object to find the NetBIOS domain name from the
' DNS domain name.
Set objTrans = CreateObject("NameTranslate")
objTrans.Init ADS_NAME_INITTYPE_GC, ""
objTrans.Set ADS_NAME_TYPE_1779, strDNSDomain
strNetBIOSDomain = objTrans.Get(ADS_NAME_TYPE_NT4)
' Remove trailing backslash.
strNetBIOSDomain = Left(strNetBIOSDomain, Len(strNetBIOSDomain) - 1)

' Read lines from the file.
Do Until objFile.AtEndOfStream
strComputer = Trim(objFile.ReadLine)
If (strComputer <> "") Then
' Convert NetBIOS name to DN.
' NetBIOS name must have "$" appended to end.
' Trap error if computer not found.
On Error Resume Next
objTrans.Set ADS_NAME_TYPE_NT4, strNetBIOSDomain & "\" & strComputer & "$"
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Computer not found: " & strComputer
Else
On Error GoTo 0
strComputerDN = objTrans.Get(ADS_NAME_TYPE_1779)
' Bind to the computer object.
Set objComputer = GetObject("LDAP://" & strComputerDN)
' Disable the computer.
objComputer.AccountDisabled = True
objComputer.SetInfo
End If
End If
Loop

Wscript.Echo "Done"

--- End Script ---