Got error object required when connecting WMI - vbscript

I want to create an Excel log file to record the hostname, IP, status of ping and the status of a WMI connection. When I try to run the script I've got an error "object required", but when I check the code I couldn't find where I should change the code.
On Error Resume Next
Set Fso = CreateObject("Scripting.FileSystemObject")
Set InputFile = Fso.OpenTextFile("file.txt", 1)
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add
intRow = 2
objExcel.Cells(1, 1).Value = "Hostname"
objExcel.Cells(1, 2).Value = "IP"
objExcel.Cells(1, 3).Value = "Ping"
objExcel.Cells(1, 4).Value = "WMI"
Do While Not (InputFile.atEndOfStream)
hostname = InputFile.ReadLine
Set WshShell = CreateObject("WScript.Shell")
Set Ping = WshShell.Run("ping -n 1 " & hostname, 0, True)
objExcel.Cells(intRow, 1).Value = hostname
Select Case Ping
Case 0 objExcel.Cells(intRow, 3).Value = "On Line"
Case 1 objExcel.Cells(intRow, 3).Value = "Off Line"
Case 2 objExcel.Cells(intRow, 3).Value = "N/A"
End Select
Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & hostname & "\root\cimv2")
Set IPconfig = objWMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
If Err.Number = 0 Then
objExcel.Cells(intRow, 4).Value = "Pass"
For Each IP In IPconfig
If Not IsNull(IP.IPAddress) Then
For i = LBound(IP.IPAddress) To UBound(IP.IPAddress)
objExcel.Cells(intRow, 2).Value = IP.IPAddress(i)
Next
Else
objExcel.Cells(intRow, 2).Value = "N/A"
End If
Next
Else
objExcel.Cells(intRow, 4).Value = Err.Description
End If
intRow = intRow + 1
Loop
objExcel.Range("A1:B1:C1:D1").Select
objExcel.Selection.Interior.ColorIndex = 19
objExcel.Selection.Font.ColorIndex = 11
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit
InputFile.Close
On Error Goto 0
Set objExcel = Nothing
Set Fso = Nothing
Set InputFile = Nothing
Set objWMIService = Nothing
Set WshShell = Nothing
Set Ping = Nothing
Set IPconfig = Nothing
MsgBox "Done Analyse"
objExcel.Quit
Wscript.Quit

Set Ping = WshShell.Run("ping -n 1 " & hostname, 0, True)
WshShell returns an integer not an object. Set is ONLY user for objects. So just delete set word.
Wmi can do it's own pinging. Here's the command line version but you can plug it in to the WMI statement you are using for NetworkAdaptor.
wmic /append:"textfile.txt" path win32_pingstatus where "address='127.0.0.1' and responsetime > 100" get responsetime,timestamprecord
For help that is same as vbscript type wmic path win32_pingstatus get /?

Related

Get disks information and output to one line

I am trying to read the information on the storage drives and would like to output the results as (on 1 line):
1/2 - Samsung Evo - 500GB - 4 partitions - C :, D :, E :, F:
2/2 - USB Transcend - 16GB - 2 partitions - G :, H:
On Error Resume Next
' Create a FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
' Provide file path
Dim result, strComputer, outFile, PropertyArr, ArrayItem
outFile = "C:\Users\MISS\Desktop\ok.txt"
' Sets computer name to the current computer name
strComputer = "."
' Setting up file to write
Set objFile = FSO.CreateTextFile(outFile, True)
' Connect to the WMI Service
Set CIMV2 = GetObject("winmgmts:" & "\\" & strComputer & "\root\CIMV2")
If Err Then
WScript.StdOut.WriteLine "Unable to access WMI Service."
WScript.Quit 32
End If
' Fetch all details from Win32_computersystem
Set Win32_DiskDrive = CIMV2.ExecQuery("Select * from Win32_DiskDrive")
PropertyArr = Array("Model","MediaType")
For Each item_PropertyArr In PropertyArr
ArrayItem = item_PropertyArr
Next
For Each item In Win32_DiskDrive
result = item.ArrayItem
WScript.Echo "Result: " & result
Next
Set FSO = Nothing
It is empty result.
To get the string output in the desired format, I would suggest using a template string and use Replace() to fill in the details.
Because you want the driveletters that are associated with each partition aswell, you need to do more than just query the Win32_DiskDrive, because that query does not return driveletters. See here
The below code should do what you want:
Option Explicit
Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objDriveLetters, objLogicalDisk
Dim outFile, strFormat, strResult, numCurrentDrive, strMediaType, strID, strQuery, strComputer
On Error Resume Next
' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"
Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)
strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )
'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
'start building the string to output
strMediaType = objDiskDrive.MediaType
If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
strResult = Replace(strFormat, "{0}", numCurrentDrive)
strResult = Replace(strResult, "{1}", colDiskDrives.Count)
strResult = Replace(strResult, "{2}", objDiskDrive.Model)
strResult = Replace(strResult, "{3}", strMediaType)
strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)
'increase the current drive counter
numCurrentDrive = numCurrentDrive + 1
'create an arraylist to capture the drive letters
Set objDriveLetters = CreateObject("System.Collections.ArrayList")
'escape the backslashes in objDiskDrive.DeviceID for the query
strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
Set colPartitions = objWMIService.ExecQuery(strQuery)
For Each objDiskPartition In colPartitions
'get the drive letter for each partition
strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
For Each objLogicalDisk In colLogicalDisks
objDriveLetters.Add objLogicalDisk.DeviceID
'objDriveLetters.Add objLogicalDisk.VolumeName
Next
Set colLogicalDisks = Nothing
Next
'add the driveletters to the output string
strResult = strResult & " - " & Join(objDriveLetters.ToArray(), ", ")
Set objDriveLetters = Nothing
Set colPartitions = Nothing
'output on screen
WScript.Echo strResult
'output to file
objFile.WriteLine strResult
Next
'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing
Update
As per your comments, you would like to not use .NET (the ArrayList) in the code. This can be done of course, but with a little bit more effort:
Option Explicit
Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objLogicalDisk
Dim outFile, strFormat, strResult, strMediaType, strID, strQuery, strComputer
Dim arrDriveLetters, numCurrentDrive, numDriveLetters
On Error Resume Next
' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"
Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)
strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )
'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
'start building the string to output
strMediaType = objDiskDrive.MediaType
If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
strResult = Replace(strFormat, "{0}", numCurrentDrive)
strResult = Replace(strResult, "{1}", colDiskDrives.Count)
strResult = Replace(strResult, "{2}", objDiskDrive.Model)
strResult = Replace(strResult, "{3}", strMediaType)
strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)
'increase the current drive counter
numCurrentDrive = numCurrentDrive + 1
'reset the dynamic array to capture the drive letters
numDriveLetters = 0
ReDim arrDriveLetters(numDriveLetters)
'escape the backslashes in objDiskDrive.DeviceID for the query
strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
Set colPartitions = objWMIService.ExecQuery(strQuery)
For Each objDiskPartition In colPartitions
'get the drive letter for each partition
strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
For Each objLogicalDisk In colLogicalDisks
ReDim Preserve arrDriveLetters(numDriveLetters)
arrDriveLetters(numDriveLetters) = objLogicalDisk.DeviceID
numDriveLetters = numDriveLetters + 1
Next
Set colLogicalDisks = Nothing
Next
'add the driveletters to the output string
strResult = strResult & " - " & Join(arrDriveLetters, ", ")
Erase arrDriveLetters
Set colPartitions = Nothing
'output on screen
WScript.Echo strResult
'output to file
objFile.WriteLine strResult
Next
'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing
The output will be something like
1/4 - Samsung SSD 750 EVO 250GB ATA Device - Fixed hard disk media - 1 partition(s) - C:
2/4 - ST3500418AS ATA Device - Fixed hard disk media - 1 partition(s) - E:
3/4 - WDC WD7501AALS-00J7B0 ATA Device - Fixed hard disk media - 1 partition(s) - D:
4/4 - Generic Ultra HS-SD/MMC USB Device - Unknown - 0 partition(s)
Hope that helps
P.S. Best run using CScript instead of WScript, to avoid having popup messages with one line at a time

Reset Network Adapter

I have here a VBScript to "toggle" my network adapter (built from a script found on the Internet).
I was wondering if maybe someone can help me convert it to a script that can "reset" (disable, then re-enable) my wireless adapter, rather than toggle it.
'~ Toggle a SPECIFIED NIC on or off
Option Explicit
Const NETWORK_CONNECTIONS = &H31&
Dim objShell, objFolder, objFolderItem, objEnable, objDisable
Dim folder_Object, target_NIC
Dim NIC, clsVerb
Dim str_NIC_Name, strEnable, strDisable
Dim bEnabled, bDisabled
'NIC name goes here VVV
str_NIC_Name = "Wi-Fi"
strEnable = "En&able"
strDisable = "Disa&ble"
' create objects and get items
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(NETWORK_CONNECTIONS)
Set objFolderItem = objFolder.Self
Set folder_Object = objFolderItem.GetFolder
Set target_NIC = Nothing
' look at each NIC and match to the chosen name
For Each NIC In folder_Object.Items
If LCase(NIC.Name) = LCase(str_NIC_Name) Then
' proper NIC is found, get it
Set target_NIC = NIC
End If
Next
bEnabled = True
Set objEnable = Nothing
Set objDisable = Nothing
For Each clsVerb In target_NIC.Verbs
'~ Wscript.Echo clsVerb
If clsVerb.Name = strEnable Then
Set objEnable = clsVerb
bEnabled = False
End If
If clsVerb.Name = strDisable Then
Set objDisable = clsVerb
End If
Next
If bEnabled Then
objDisable.DoIt
Else
objEnable.DoIt
End If
'~ Give the connection time to change
WScript.Sleep 5000
I think it's better to use WMI (Windows Management Instrumentation).
Here is a sample script:
Option Explicit
dim ComputerName
dim WMIService, NIC
dim ConnectionName
ComputerName = "."
ConnectionName = "Ethernet"
if not IsElevated then
WScript.Echo "Please run this script with administrative rights!"
WScript.Quit
end if
On Error Resume Next
Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\cimv2")
Set NIC = WMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID = '" & ConnectionName & "'").ItemIndex(0)
if NIC is nothing then
WScript.Echo "NIC not found!"
WScript.quit
end if
WScript.Echo "NIC Current status: " & iif(NIC.NetEnabled, "Enabled", "Disabled") & vbcrlf
if NIC.NetEnabled then
WScript.Echo "Disabling NIC..."
NIC.Disable
WScript.Sleep 1000
WScript.Echo "Enabling NIC..."
NIC.Enable
end if
function iif(cond, truepart, falsepart)
if cond then iif=truepart else cond=falsepart
end function
function IsElevated()
On Error Resume Next
CreateObject("WScript.Shell").RegRead("HKEY_USERS\s-1-5-19\")
IsElevated = (err.number = 0)
end function

Permission Denied Error 800A0046 'objIE.Document.parentWindow.screen'

I have a script that I put together for my users a few years ago for them to log onto to the company drive shares after they had logged into the VPN. The script has worked well over the years with a few tweaks needed here and there due to IE version upgrades. As of today I can no longer get the script to function properly the Error is:
Line: 93
Char: 5
Error: Permission denied: 'objIE.Document.parentWindow.screen'
Code: 800A0046
Source: Microsoft VBScript runtime error
I'm not sure what has changed but after doing multiple searches on the error codes and other items I figured I'd post it here and see if any of you can help me with this problem.
dim WshNetwork
Dim arrFileLines()
'On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("Drive Shares.txt", 1)
If Not err.number = 0 then
WScript.Echo "Drive Shares.txt was not found. Please ensure that it is in the same directory as this script file"
WScript.Quit
End If
NumElements = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(NumElements)
arrFileLines(NumElements) = objFile.ReadLine
NumElements = NumElements + 1
Loop
objFile.Close
strPw = GetPassword()
If strPw = "" Then
wScript.Quit
End If
SplitPasswd = Split(StrPW,"*",2)
username = "DEFAULT\" & SplitPasswd(0)
password = SplitPasswd(1)
Set WshNetwork = Wscript.CreateObject("WScript.Network")
For Count = 0 to (NumElements - 1)
SplitDriveInfo = Split(arrFileLines(Count)," ",2)
DriveLetter = SplitDriveInfo(0)
Share = SplitDriveInfo(1)
ExitCode = WshNetwork.MapNetworkDrive(DriveLetter, Share, false, username, password)
ErrorHandler(err.number)
Next
Sub ErrorHandler(ErrorNumber)
Select Case ErrorNumber
Case 0
'OK
Exit Sub
Case -2147024811
'Already Mapped Continue
Exit Sub
Case -2147024843
'No Connection
WScript.Echo "No connection found. Confirm you have an internet connection and that you have the VPN connected."
WScript.Quit
Case -2147024829
'Share not available
WScript.Echo "The drive share you are trying to connect to does not exist on this server."
WScript.Quit
Case -2147023570
'Invalid username or password
WScript.Echo "Invalid username or password. Please try again."
WScript.quit
Case Else
WScript.Echo "Unknown error: " & CStr(ErrorNumber)
WScript.Quit
End Select
End Sub
Function GetPassword()
Dim objIE
Set objIE = CreateObject( "InternetExplorer.Application" )
objIE.Navigate "about:blank"
objIE.Document.Title = "Login Credentials"
objIE.ToolBar = False
objIE.Resizable = False
objIE.StatusBar = False
objIE.Width = 320
objIE.Height = 320
With objIE.document.parentWindow.screen
objIE.Left = (.availwidth - objIE.Width ) \ 2
objIE.Top = (.availheight - objIE.Height) \ 2
End With
objIE.Document.Body.InnerHTML = "<DIV align=""center""><P>Please enter your credentials</P>" & vbCrLf _
& "<DIV align=""center""><P>Username</P>" & vbCrLf _
& "<P><INPUT TYPE=""Username"" SIZE=""20"" " _
& "ID=""UserName""></P>" & vbCrLf _
& "<DIV align=""center""><P>Password</P>" & vbCrLf _
& "<P><INPUT TYPE=""password"" SIZE=""20"" " _
& "ID=""Password""></P>" & vbCrLf _
& "<P><INPUT TYPE=""hidden"" ID=""OK"" " _
& "NAME=""OK"" VALUE=""0"">" _
& "<INPUT TYPE=""submit"" VALUE="" OK "" " _
& "OnClick=""VBScript:OK.Value=1""></P></DIV>"
objIE.Visible = True
Do While objIE.Document.All.OK.Value = 0
WScript.Sleep 200
Loop
GetPassword = objIE.Document.All.UserName.Value & "*" & objIE.Document.All.Password.Value
objIE.Quit
Set objIE = Nothing
End Function
Any help with this would be greatly appreciated.
Microsoft released hotfix:[KB3025390] http://support.microsoft.com/kb/3025390
I can confirm uninstalling this update will resolve issue if it worked just prior to December 17th, 2014.
I had a similar problem with an HTA program using IE 11 and the With objIE.Document.ParentWindow.Screen command.
I found adding objIE.left = 910 and objIE.top and removed the With objIE.Document.ParentWindow.Screen section and now the IE Windows opens fine.
Sub AdditionalComputerInfo
'v3.00 - Changed to HTML Output
strComputer = trim(txtComputerName.Value)
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Navigate("about:blank")
objIE.ToolBar = 0
objIE.StatusBar = 0
objIE.addressbar = 0
objIE.Width = 650
objIE.Height = 900
'added v3.02
objIE.Left = 910
objIE.Top = 20
objIE.Document.Title = " " & uCase(strComputer) & " Information"
'With objIE.Document.ParentWindow.Screen removed in version 3.02
' objIE.Left = 910
' objIE.Top = 20
'End With
Set objDoc = objIE.Document.Body

VB script to get IP address from Ping command

I'm trying to write a script to show every server ipaddress that I put into a text file. I've been looking online and came across the script below. What I need is instead of it showing 'online' I need it show show the actual IP address of each server in the text file. I've been looking for an answer to this for a while now, I've pretty new to vbs so I'm sorry if the script below is wrong or simple. This does open an excel doc which I'm pretty happy with.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add
intRow = 2
objExcel.Cells(1, 1).Value = "Server Name"
objExcel.Cells(1, 2).Value = "IP Address"
Set Fso = CreateObject("Scripting.FileSystemObject")
Set InputFile = fso.OpenTextFile("MachineList.Txt")
Do While Not (InputFile.atEndOfStream)
HostName = InputFile.ReadLine
Set WshShell = WScript.CreateObject("WScript.Shell")
Ping = WshShell.Run("ping -n 1 " & HostName, 0, True)
objExcel.Cells(intRow, 1).Value = HostName
Select Case Ping
Case 0 objExcel.Cells(intRow, 2).Value = "On Line"
Case 1 objExcel.Cells(intRow, 2).Value = "Off Line"
End Select
intRow = intRow + 1
Loop
objExcel.Range("A1:B1").Select
objExcel.Selection.Interior.ColorIndex = 19
objExcel.Selection.Font.ColorIndex = 11
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit
Edited because my original statement wasn't accurate. You can get the StdOut of a process launched with exec like this:
Option Explicit
Const HOST_FILE = "MachineList.txt"
Dim shl, exe, exl, fso, file
Dim iRow, out, host
Set shl = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FilesystemObject")
Set exl = CreateObject("Excel.Application")
exl.Workbooks.Add
iRow = 2
exl.Cells(1,1).Value = "Server Name"
exl.Cells(1,2).Value = "IP Address"
Set file = fso.OpenTextFile(HOST_FILE)
While not file.AtEndOfStream
host = Trim(file.ReadLine)
exl.Cells(iRow,1).Value = host
Set exe = shl.Exec("%COMSPEC% /c ping -n 1 """ & host & """ | Find ""statistics for""")
If Not exe.StdOut.AtEndOfStream Then
out = exe.StdOut.ReadAll
exl.Cells(iRow,2).Value = getIP(out)
Else
exl.Cells(iRow,2).Value = "Ping Failed"
End If
iRow = iRow + 1
Wend
exl.Visible = True
Set exl = Nothing
Set shl = Nothing
Set fso = Nothing
Set exe = Nothing
WScript.Quit
Function getIP(text)
Dim s
s = Mid(text, Len("Ping statistics for ") + 1)
getIP = Trim(Replace(s,":",""))
End Function
However, the exec function has no WindowStyle option, so you'll see the command processor flash up for every time it runs ping.
You can use the RUN method of the script shell instead and have the ping statement output to a text file. Then read the text file once the ping statement completes and get the info that way.
Set objWSH = CreateObject("WScript.Shell")
objWSH.Run "%COMSPEC% /c ping -n 1 """ & host & """ | Find ""statistics for"" > temp.txt", 0, True
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("temp.txt", 1)
out = Trim(objFile.ReadAll)
If out <> "" Then
' Read ping data
Else
' Ping failed to run
End If
Or something along those line. That should get you on the right track.

vbscript, validate a user is in active directory by schema attribute

I'm trying to write a vb script that prompts a user for a schema attribute which I'll call bID and checks that the person with that bID is in active directory. I really have no idea how to get started, there are plenty of examples on how to query active directory users but I havent found a good one regarding checking against specific attributes. Any help/suggestions are greatly appreciated!
UPDATE:
ok heres my code so far, doesnt error out and returns 0, but I dont get a wscript.echo of the distinguished name for some reason. I included a few debugging wscript.echo's and it seems to never get into the while loop. Any ideas?
Option Explicit
GetUsers "CN=users,DC=example,DC=example,DC=example,DC=com","123456"
Function GetUsers(domainNc, ID)
Dim cnxn
Set cnxn = WScript.CreateObject("ADODB.Connection")
cnxn.Provider = "ADsDSOObject"
cnxn.Open "Active Directory Provider"
Dim cmd
Set cmd = WScript.CreateObject("ADODB.Command")
cmd.ActiveConnection = cnxn
cmd.CommandText = "<LDAP://" & domainNc & ">;(&(objectCategory=user)(objectClass=user) (employeeNumber=" & ID & "));distinguishedName;subtree"
WScript.Echo cmd.CommandText
cmd.Properties("Page Size") = 100
cmd.Properties("Timeout") = 30
cmd.Properties("Cache Results") = False
WScript.Echo "setting cmd.properties"
Dim rs
Set rs = cmd.Execute
WScript.Echo "rs object set"
While Not rs.eof
On Error Resume Next
WScript.Echo "while loop start"
Wscript.Echo rs.fields("distinguishedName".Value)
rs.MoveNext
If (Err.Number <> 0) Then
WScript.Echo vbCrLf& "Error # "& CStr(Err.Number)& " "& Err.Description
Else
On Error GoTo 0
End If
Wend
WScript.Echo "while loop end"
rs.close
WScript.Echo "rs object closed"
cnxn.Close
Set rs = Nothing
Set cmd = Nothing
Set cnxn = Nothing
End Function
Here's some vbscript that will find all users with bID=FooVal and write their DN out
Function GetUsers(domainNc, bIdVal)
Dim cnxn
Set cnxn = WScript.CreateObject("ADODB.Connection")
cnxn.Provider = "ADsDSOObject"
cnxn.Open "Active Directory Provider"
Dim cmd
Set cmd = WScript.CreateObject("ADODB.Command")
cmd.ActiveConnection = cnxn
cmd.CommandText = "<LDAP://" & domainNc & ">;(&(objectCass=user)(objectCategory=person)(bid=" & bidVal & "));distinguishedName;subtree"
cmd.Properties("Page Size") = 100
cmd.Properties("Timeout") = 30
cmd.Properties("Cache Results") = False
Dim rs
Set rs = cmd.Execute
While Not rs.eof
Wscript.Echo rs.fields("distinguishedName").Value
rs.MoveNext
Wend
rs.close
cnxn.Close
Set rs = Nothing
Set cmd = Nothing
Set cnxn = Nothing
End Function

Resources