'****************************************************
'		Script Witten by Larry Heintz
'		April 2006 www.windowsadminscripts.com
' This script will enumerate Computers in a Active
' Directory Domain. All the information is written
' to a comma delimited text file.
'
' Script Usage: cscript adcomputers.vbs /ad:[AD Domain]
'****************************************************
Dim args,ad,logPath
Set args = Wscript.Arguments.Named
ad = args.Item("ad")
logPath = getLogPath()

if wscript.arguments.count = 0 then
	wscript.echo "Script Usage: cscript adcomputers.vbs /ad:[AD Domain]"
else
	if ad = "" then
		ad = getDomainName()
	else
		ad = ad
	end if
	Call enumComputers(ad)
end if

Function enumComputers(ad)
On Error Resume Next
Dim objcomputer,ecomputer,count
count = 0
wscript.echo "Starting script..."
Set objcomputer = GetObject("WinNT://" & ad)
if not (errorChecking (ad)) then
	objcomputer.filter = Array("computer")
		For Each ecomputer in objcomputer
			count = count + 1
			Call writetoLog(ecomputer.name,ad)
			wscript.echo ecomputer.name
		next
end if
Set objcomputer = nothing
wscript.echo ""
wscript.echo "There are " & count & " Computers in the " & ucase(ad) & " Active Directory Domain"
wscript.echo "Ending script..."
End Function

Function writetoLog(computer,ad)
Dim FSO,objFSOwriteline
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFSOwriteline = FSO.OpenTextFile(logPath & "\computers_" & ad & ".txt", 8,True)
	objFSOwriteline.WriteLine(computer & "," & ad)
	objFSOwriteline.close
Set objFSOwriteline = nothing
Set FSO = nothing
End Function

Function getLogPath()
Dim temp,temp2
temp = split(wscript.scriptfullname,"\")
for i = 0 to ubound(temp) - 1
	temp2 = temp2 & temp(i) & "\"
next
getLogPath = temp2
End Function

Function getComputer()
	Dim objNet
	Set objNet = WScript.CreateObject("WScript.Network") 
	getComputer = objNet.ComputerName 
	Set objNet = Nothing 
End Function

Function getDomainName()
    Dim QConfigSet, qsetreturn
    Set QConfigSet = GetObject("winmgmts:{impersonationLevel=impersonate}\\" & getComputer() & "\root\cimv2").ExecQuery("SELECT * FROM Win32_ComputerSystem")
    For Each qsetreturn In QConfigSet
        getDomainName = qsetreturn.domain
    Next
    Set QConfigSet = Nothing
End Function

Function errorChecking(ad) 
errorChecking = False 
if err.number <> 0 then 
	wscript.echo "Unable to connect to " & ucase(ad) & " AD Domain"
	err.Clear () 
	errorChecking = True
end if 
end Function
