Solved

Querying the domain /server

Posted on 2013-01-28
32
715 Views
Last Modified: 2013-02-04
I must have close my previous question too quickly. After I commented out the "On error' . I got the following error message .

Wrong number of arguments or invalid property assignent : 'Get Object'
800A01C2

'On Error Resume Next
strUser = "?????"
strPassword = "?????"
arrComputers = Array("?????.??????.co.nz")

For Each strComputer In arrComputers
   WScript.Echo
   WScript.Echo "=========================================="
   WScript.Echo "Computer: " & strComputer
   WScript.Echo "=========================================="
   wscript.echo strcomputer
   Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2", strUser, strPassword)
   objWMIService.Security_.authenticationLevel = WbemAuthenticationLevelPktPrivacy

   Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ServerSession",,48)

   For Each objItem In colItems
      WScript.Echo "ActiveTime: " & objItem.ActiveTime
      WScript.Echo "Caption: " & objItem.Caption
      WScript.Echo "ClientType: " & objItem.ClientType
      WScript.Echo "ComputerName: " & objItem.ComputerName
      WScript.Echo "Description: " & objItem.Description
      WScript.Echo "IdleTime: " & objItem.IdleTime
      WScript.Echo "InstallDate: " & WMIDateStringToDate(objItem.InstallDate)
      WScript.Echo "Name: " & objItem.Name
      WScript.Echo "ResourcesOpened: " & objItem.ResourcesOpened
      WScript.Echo "SessionType: " & objItem.SessionType
      WScript.Echo "Status: " & objItem.Status
      WScript.Echo "TransportName: " & objItem.TransportName
      WScript.Echo "UserName: " & objItem.UserName
      WScript.Echo
   Next
Next
Wscript.echo " Job Done"
0
Comment
Question by:Bianchi928
  • 17
  • 15
32 Comments
 
LVL 65

Expert Comment

by:RobSampson
ID: 38829439
Hi, you need to use the SWbemLocator object to use alternate credentials.

Regards,

Rob.

'On Error Resume Next
Const WbemAuthenticationLevelPktPrivacy = 6

strUser = "?????"
strPassword = "?????"
arrComputers = Array("?????.??????.co.nz")

For Each strComputer In arrComputers
   WScript.Echo
   WScript.Echo "=========================================="
   WScript.Echo "Computer: " & strComputer
   WScript.Echo "=========================================="
   wscript.echo strcomputer
   'Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2", strUser, strPassword)
	Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
	Set objWMIService = objWbemLocator.ConnectServer(strComputer, "\root\CIMV2", strUser, strPassword)
	objWMIService.Security_.authenticationLevel = WbemAuthenticationLevelPktPrivacy

   Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ServerSession",,48)

   For Each objItem In colItems
      WScript.Echo "ActiveTime: " & objItem.ActiveTime
      WScript.Echo "Caption: " & objItem.Caption
      WScript.Echo "ClientType: " & objItem.ClientType
      WScript.Echo "ComputerName: " & objItem.ComputerName
      WScript.Echo "Description: " & objItem.Description
      WScript.Echo "IdleTime: " & objItem.IdleTime
      WScript.Echo "InstallDate: " & WMIDateStringToDate(objItem.InstallDate)
      WScript.Echo "Name: " & objItem.Name
      WScript.Echo "ResourcesOpened: " & objItem.ResourcesOpened
      WScript.Echo "SessionType: " & objItem.SessionType
      WScript.Echo "Status: " & objItem.Status
      WScript.Echo "TransportName: " & objItem.TransportName
      WScript.Echo "UserName: " & objItem.UserName
      WScript.Echo
   Next
Next 
Wscript.echo " Job Done" 

Open in new window

0
 

Author Comment

by:Bianchi928
ID: 38829490
Hi Rob...I can see that you're scored a few points on the weekend. Happy New Year !!

Are you affected by the flood ?

Anyway, I have a type mismatch on line 28.

Now, what I really wanted to extract is the following..I don't know if I'm doing the right thing.

I have a Domain name in NZ and I want to know all the computers actively connected to it.

I need to run an audit and come up with the following infos.

BY username, computer name & ip address and anything else that can be helpful.

Unless you have better ideas on how to get these infos.

Thanks
Cheers
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38829523
Hi, thanks.  Happy New Year to you as well.  I'm not affected by the flood, being in Melbourne, Victoria, but the smoke from the East Gippsland fires has come a long way!

As for the script error, this will fix that, since I've added the WMIDateStringToDate function
'On Error Resume Next
Const WbemAuthenticationLevelPktPrivacy = 6

strUser = "?????"
strPassword = "?????"
arrComputers = Array("?????.??????.co.nz")

For Each strComputer In arrComputers
   WScript.Echo
   WScript.Echo "=========================================="
   WScript.Echo "Computer: " & strComputer
   WScript.Echo "=========================================="
   wscript.echo strcomputer
   'Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2", strUser, strPassword)
	Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
	Set objWMIService = objWbemLocator.ConnectServer(strComputer, "\root\CIMV2", strUser, strPassword)
	objWMIService.Security_.authenticationLevel = WbemAuthenticationLevelPktPrivacy

   Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ServerSession",,48)

   For Each objItem In colItems
      WScript.Echo "ActiveTime: " & objItem.ActiveTime
      WScript.Echo "Caption: " & objItem.Caption
      WScript.Echo "ClientType: " & objItem.ClientType
      WScript.Echo "ComputerName: " & objItem.ComputerName
      WScript.Echo "Description: " & objItem.Description
      WScript.Echo "IdleTime: " & objItem.IdleTime
      WScript.Echo "InstallDate: " & WMIDateStringToDate(objItem.InstallDate)
      WScript.Echo "Name: " & objItem.Name
      WScript.Echo "ResourcesOpened: " & objItem.ResourcesOpened
      WScript.Echo "SessionType: " & objItem.SessionType
      WScript.Echo "Status: " & objItem.Status
      WScript.Echo "TransportName: " & objItem.TransportName
      WScript.Echo "UserName: " & objItem.UserName
      WScript.Echo
   Next
Next 
Wscript.echo " Job Done" 

Function WMIDateStringToDate(dtmDate)
WScript.Echo dtm: 
	WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
	Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
	& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
End Function

Open in new window


but as for getting the information you want....this script will show you information that would be similar to that which you see in the Computer Management ---> Sessions console.  This would show you which users had open sessions to a specific server at that point in time.  That may be good enough, but probably isn't an overall picture.

What you may be better off doing is running a report from that domain about which computers have "logged on" to the domain in the last 90 days or something....but it depends on what you're after.

Regards,

Rob
0
 

Author Comment

by:Bianchi928
ID: 38829554
Hi

Thanks.

Let me give you the complete picture. In NZ (an extension oif our business),  unlike us, theircomputers have joined the Domain with some funny Computer Names instead of the Service Tag.  I need to account for all  the computers and know who is using it and  hence know the location , ip address , etc so that I can build up an asset register.

See how you can help

Thanks
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38829675
Hmmm....this sort of capturing might be better done as a logon script, one that would write to text files (of each computer name) on a network share, and log the username, ip address, AD site name, local computer description, etc.

Do you think that would work better?  Otherwise, I'd be worried that you wouldn't get the whole picture, if you have people on holiday or something.  But if you're happy that the vast majority of computers are on when you run the script, we could do a network scan and gather the info as well.

Regards,

Rob.
0
 

Author Comment

by:Bianchi928
ID: 38829710
You are reading my mind. I will definitely need both. The logon script will be very helpful  . A net work scan also will help me whenver I run it during working hours.

See  what you can do to help. Since it invloves more work, I've increased the points.

Thanks
Cheers
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38829761
OK, to start with, here's a script that I use at logon, that records to a %username%.txt file specified by this line:
strOutputFile = "\\fileserver\UserLogins$\" & strUserName & ".txt"

You can change the array of valid subnets that you want to record for by changing the subnets in this section:
arrSubnets = Array( _
      "172.16.1.", _
      "172.16.2.", _
      "172.16.3." _
      )

In each text file you will see the IP Address, Hostname, and Date that the script was run, in the file for %username%, so if you want to know who logged on where, you can check the log file.

If you want to make it record into %computername% text files instead, and have the detail use %username% instead, just change this line:
strOutputFile = "\\fileserver\UserLogins$\" & strUserName & ".txt"

to this
strOutputFile = "\\fileserver\UserLogins$\" & strComputerName & ".txt"

and also this line
objFile.Write(Pad_String(strValidIP, 20, "Right", " ") & "|  " & Pad_String(strHostName, 24, "Right", " ") & "|  " & Pad_String(Now, 28, "Right", " ") & "| " & strAction & VbCrLf & strContents)

to this
objFile.Write(Pad_String(strValidIP, 20, "Right", " ") & "|  " & Pad_String(strUserName, 24, "Right", " ") & "|  " & Pad_String(Now, 28, "Right", " ") & "| " & strAction & VbCrLf & strContents)


Let's see how that goes as a logon script, and if it goes well, I'll have the same script do a network scan as well.

Regards,

Rob.

Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Set objNetwork = CreateObject("WScript.Network")

strUserName = objNetwork.UserName
strHostName = objNetwork.ComputerName

' /////// Define the text file name as the name of the user //////////
strOutputFile = "\\fileserver\UserLogins$\" & strUserName & ".txt"

' Enter your valid network subnets here (avoids recording of local wireless connections)
arrSubnets = Array( _
	"172.16.1.", _
	"172.16.2.", _
	"172.16.3." _
	)
	
' For the script arguments, you can pass "logon", or "logoff" and it will be recorded in the text file so you know why it executed
If WScript.Arguments.Count > 0 Then
	strAction = WScript.Arguments.Item(0)
Else
	strAction = ""
End If

strComputer = "."

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
Set colComputerIP = objWMIService.ExecQuery ("Select * from Win32_NetworkAdapterConfiguration")
 
For Each IPConfig In colComputerIP
	If Not IsNull(IPConfig.IPAddress) Then 
        For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)
                strIPAddress = strIPAddress & "IP Address: " & IPConfig.IPAddress(intIPCount) & "~"
		Next
	End If
Next

strValidIP = "UNKNOWN"
For Each strSubnet In arrSubnets
	If InStr(strIPAddress, strSubnet) > 0 Then
		strValidIP = Mid(strIPAddress, InStr(strIPAddress, strSubnet), InStr(InStr(strIPAddress, strSubnet), strIPAddress, "~") - InStr(strIPAddress, strSubnet))
	End If
Next

If Len(strValidIP) > 1 And Right(strValidIP, 1) = "~" Then
	strValidIP = Left(strValidIP, Len(strValidIP) - 1)
End If

On Error Resume Next

'/////// Open the user's text file for reading first to be able to count the number of lines ///////
Set objFile = objFSO.OpenTextFile (strOutputFile, ForReading, True)

'////// Set this value to the maximum number of entries allowed per user's text file
'////// Set this value to 0 or -1 to have unlimited lines
intMaxLinesAllowed = -1

strContents = ""
strContents = objFile.ReadAll

If Len(strContents) > 0 Then
	arrLinesInFile = Split(strContents, vbCrLf)
	If intMaxLinesAllowed > 0 Then
		If UBound(arrLinesInFile) > (intMaxLinesAllowed - 1) Then
			strContents = ""
			For intLineCount = 0 To (intMaxLinesAllowed - 2)
				strContents = strContents & arrLinesInFile(intLineCount) & VbCrLf
			Next
			strContents = strContents & arrLinesInFile((intMaxLinesAllowed - 1))
		End If
	End If
End If

Set objFile = objFSO.OpenTextFile (strOutputFile, ForWriting, True)
objFile.Write(Pad_String(strValidIP, 20, "Right", " ") & "|  " & Pad_String(strHostName, 24, "Right", " ") & "|  " & Pad_String(Now, 28, "Right", " ") & "| " & strAction & VbCrLf & strContents)

objFile.Close

On Error Goto 0

Function Pad_String(strOriginalString, intTotalLengthRequired, strDirection, strCharacterToPadWith)
	Select Case LCase(strDirection)
		Case "left"
			Pad_String = Right(String(intTotalLengthRequired, strCharacterToPadWith) & strOriginalString, intTotalLengthRequired)
		Case "right" 
			Pad_String = Left(strOriginalString & String(intTotalLengthRequired, strCharacterToPadWith), intTotalLengthRequired)
	End Select
End Function

Open in new window

0
 

Author Comment

by:Bianchi928
ID: 38832596
Thanks Rob . Unfortunately I won't be able to test the logon script before Saturday. In the meantime , send me the Network scan one which I will be able to test straight away. Sorry to be a pain

Cheers
0
 

Author Comment

by:Bianchi928
ID: 38837336
Hello Rob,

I've been able to force the issue and have the login scripts tested. Very happy with the results , specially that it just appends to teh output file.

Whenever you have a spare time, forward me the script for the Network Scan .

Thanks
Cheers
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38842758
Hi, sorry for my delay.  I have written a network scan script (which is very different in code) that writes roughly the same info to a single CSV file, overwriting each time.

Is there any other info you want added to the script?

Regards,

Rob,

' Enter the first three octets of the subnet to scan
strScanSubnet = "10.0.1."
strStart = "1"
strEnd = "255"

' Enter the output file name (CSV format)
strOutputFile = "ComputerInfo.csv"

Const ForWriting = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutput = objFSO.CreateTextFile(strOutputFile, True)
objOutput.WriteLine """IP Address"",""Hostname"",""Current User"""

If Right(strScanSubnet, 1) <> "." Then strScanSubnet = strScanSubnet & "."
For intNode = strStart To strEnd
	strIPAddress = strScanSubnet & CStr(intNode)
	If Ping(strIPAddress) = True Then
		objOutput.WriteLine """" & strIPAddress & """,""" & GetHostName(strIPAddress) & """,""" & GetCurrentUser(strIPAddress) & """"
	Else
		objOutput.WriteLine """" & strIPAddress & """,""<OFFLINE>"",""<OFFLINE>"""
	End If
Next
objOutput.Close

WScript.Echo "Done. Please see " & strOutputFile

Function GetCurrentUser(strComputer)
	Dim objWMIService, colComputer, objComputer, strUser
	On Error Resume Next
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
	Set colComputer = objWMIService.ExecQuery("Select Username from Win32_ComputerSystem")
	strUser = ""
	For Each objComputer In colComputer
	    strUser = objComputer.UserName
	Next
	If Err.Number <> 0 Then strUser = "WMI Error " & Err.Number & ": " & Err.Description
	Err.Clear
	On Error GoTo 0
	GetCurrentUser = strUser
End Function

Function GetHostName(strIPAddress)
	Dim objWMIService, colComputer, objComputer, strComputerName
	On Error Resume Next
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strIPAddress & "\root\cimv2") 
	Set colComputer = objWMIService.ExecQuery("Select Name from Win32_ComputerSystem")
	strComputerName = ""
	For Each objComputer In colComputer
	    strComputerName= objComputer.Name
	Next
	If Err.Number <> 0 Then strUser = "WMI Error " & Err.Number & ": " & Err.Description
	Err.Clear
	On Error GoTo 0
	GetHostName = strComputerName
End Function

Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
	Else
		Ping = False
	End If
End Function

Open in new window

0
 

Author Comment

by:Bianchi928
ID: 38849313
Hi Rob,

Don't worry about the delay. I will test it today (04/02/2013) and get back to you asap

Thanks
Cheers
0
 

Author Comment

by:Bianchi928
ID: 38849745
Hi Rob

I did a test this morning and it seems that something is wrong somewhere...I've just pasted part of the output file

10.24.20.239            WMI Error 451: Object not a collection
10.24.20.240      DRFB62S      SPT2000\cis0794
10.24.20.241            WMI Error 451: Object not a collection
10.24.20.242      <OFFLINE>      <OFFLINE>
10.24.20.243      <OFFLINE>      <OFFLINE>
10.24.20.244      <OFFLINE>      <OFFLINE>
10.24.20.245            WMI Error 451: Object not a collection
10.24.20.246      <OFFLINE>      <OFFLINE>
10.24.20.247      <OFFLINE>      <OFFLINE>
10.24.20.248      <OFFLINE>      <OFFLINE>


Most of the entries in the output file contains these errors. But I can see mine (10.24.20.240) coming up. Any reason ?
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38849820
That's a little strange.  Are you running the script with an account that has admin rights to the remote pcs?  Are you running with elevated privileges (Vista or higher)?

Try this for a small logging change

Regards,

Rob,

' Enter the first three octets of the subnet to scan
strScanSubnet = "172.16.4."
strStart = "1"
strEnd = "10"

' Enter the output file name (CSV format)
strOutputFile = "ComputerInfo.csv"

Const ForWriting = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutput = objFSO.CreateTextFile(strOutputFile, True)
objOutput.WriteLine """IP Address"",""Hostname"",""Current User"""

If Right(strScanSubnet, 1) <> "." Then strScanSubnet = strScanSubnet & "."
For intNode = strStart To strEnd
	strIPAddress = strScanSubnet & CStr(intNode)
	If Ping(strIPAddress) = True Then
		objOutput.WriteLine """" & strIPAddress & """,""" & GetHostName(strIPAddress) & """,""" & GetCurrentUser(strIPAddress) & """"
	Else
		objOutput.WriteLine """" & strIPAddress & """,""<OFFLINE>"",""<OFFLINE>"""
	End If
Next
objOutput.Close

WScript.Echo "Done. Please see " & strOutputFile

Function GetCurrentUser(strComputer)
	Dim objWMIService, colComputer, objComputer, strUser
	On Error Resume Next
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
	Set colComputer = objWMIService.ExecQuery("Select Username from Win32_ComputerSystem")
	strUser = ""
	For Each objComputer In colComputer
	    strUser = objComputer.UserName
	Next
	If Err.Number <> 0 Then strUser = "(GetCurrentUser) WMI Error " & Err.Number & ": " & Err.Description
	Err.Clear
	On Error GoTo 0
	GetCurrentUser = strUser
End Function

Function GetHostName(strComputerIP)
	Dim objWMIService, colComputer, objComputer, strComputerName
	On Error Resume Next
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputerIP & "\root\cimv2") 
	Set colComputer = objWMIService.ExecQuery("Select Name from Win32_ComputerSystem")
	strComputerName = ""
	For Each objComputer In colComputer
	    strComputerName= objComputer.Name
	Next
	If Err.Number <> 0 Then strUser = "(GetHostName) WMI Error " & Err.Number & ": " & Err.Description
	Err.Clear
	On Error GoTo 0
	GetHostName = strComputerName
End Function

Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
	Else
		Ping = False
	End If
End Function

Open in new window

0
 

Author Comment

by:Bianchi928
ID: 38849834
NO, I'm running it as myself. But I can run it with as someone who has got admin rights.  what are the changes needed to pass on the user and password
0
 

Author Comment

by:Bianchi928
ID: 38849847
I just ran the new script . Down below is part of the output file

IP Address      Hostname      Current User
10.24.20.64            (GetCurrentUser) WMI Error 451: Object not a collection
10.24.20.65            (GetCurrentUser) WMI Error 451: Object not a collection
10.24.20.66            (GetCurrentUser) WMI Error 451: Object not a collection
10.24.20.67      <OFFLINE>      <OFFLINE>


Now, I can pin 10.24.20.64..that's strange
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38849850
You won't need to change anything in the script (or more accurately, I haven't put in the code to use alternate credentials), but what you can do is run cmd.exe as a different user, then type
cscript "C:\Scripts\NetworkScan.vbs"

Rob.
0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
LVL 65

Expert Comment

by:RobSampson
ID: 38849851
It's probably more of a rights issue.  Try it as a different user, and see what you get.

Rob.
0
 

Author Comment

by:Bianchi928
ID: 38849875
I just had it run under admin login and it comes up with the same error message.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38849881
That's odd.  It works for me....can you try this code, it has just a tiny bit more granular logging.

Regards,

Rob,

' Enter the first three octets of the subnet to scan
strScanSubnet = "172.16.4."
strStart = "1"
strEnd = "10"

' Enter the output file name (CSV format)
strOutputFile = "ComputerInfo.csv"

Const ForWriting = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutput = objFSO.CreateTextFile(strOutputFile, True)
objOutput.WriteLine """IP Address"",""Hostname"",""Current User"""

If Right(strScanSubnet, 1) <> "." Then strScanSubnet = strScanSubnet & "."
For intNode = strStart To strEnd
	strIPAddress = strScanSubnet & CStr(intNode)
	If Ping(strIPAddress) = True Then
		objOutput.WriteLine """" & strIPAddress & """,""" & GetHostName(strIPAddress) & """,""" & GetCurrentUser(strIPAddress) & """"
	Else
		objOutput.WriteLine """" & strIPAddress & """,""<OFFLINE>"",""<OFFLINE>"""
	End If
Next
objOutput.Close

WScript.Echo "Done. Please see " & strOutputFile

Function GetCurrentUser(strComputer)
	Dim objWMIService, colComputer, objComputer, strUser
	On Error Resume Next
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
	If Err.Number = 0 Then
		Set colComputer = objWMIService.ExecQuery("Select Username from Win32_ComputerSystem")
		strUser = ""
		For Each objComputer In colComputer
		    strUser = objComputer.UserName
		Next
	End If
	If Err.Number <> 0 Then strUser = "(GetCurrentUser) WMI Error " & Err.Number & ": " & Err.Description
	Err.Clear
	On Error GoTo 0
	GetCurrentUser = strUser
End Function

Function GetHostName(strComputerIP)
	Dim objWMIService, colComputer, objComputer, strComputerName
	On Error Resume Next
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputerIP & "\root\cimv2")
	If Err.Number = 0 Then
		Set colComputer = objWMIService.ExecQuery("Select Name from Win32_ComputerSystem")
		strComputerName = ""
		For Each objComputer In colComputer
		    strComputerName= objComputer.Name
		Next
	End If
	If Err.Number <> 0 Then strComputerName = "(GetHostName) WMI Error " & Err.Number & ": " & Err.Description
	Err.Clear
	On Error GoTo 0
	GetHostName = strComputerName
End Function

Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
	Else
		Ping = False
	End If
End Function

Open in new window

0
 

Author Comment

by:Bianchi928
ID: 38852897
Hi Rob,

That's weird. I got the Administrator himself to run  it and it comes up with this error. If I hardcode his IP Address in the script , it just works fine. But if I hardcode my IP address in the script it will fail.

IP Address      Hostname      Current User
10.24.20.240      (GetHostName) WMI Error 462: The remote server machine does not exist or is unavailable      (GetCurrentUser) WMI Error 462: The remote server machine does not exist or is unavailable

So in this case , 240 is mine

Thanks
Cheers
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38853055
So it's only able, via WMI, to connect to the local machine.  Have you had success with other WMI based scripts before?  This error usually indicates a communication problem with WMI.

Rob.
0
 

Author Comment

by:Bianchi928
ID: 38853285
Always had success with WMI. I've rerun the script and now it's showing a few good infos as well as plenty of failures.. Check it out
ComputerInfo.csv
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 500 total points
ID: 38853335
Hmm. I've added the Security and Backup privileges to the WMI moniker to see if that helps.  For the ips that say it can't connect, can you verify they are windows machines that you can access?

Rob,

' Enter the first three octets of the subnet to scan
strScanSubnet = "172.16.4."
strStart = "1"
strEnd = "10"

' Enter the output file name (CSV format)
strOutputFile = "ComputerInfo.csv"

Const ForWriting = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutput = objFSO.CreateTextFile(strOutputFile, True)
objOutput.WriteLine """IP Address"",""Hostname"",""Current User"""

If Right(strScanSubnet, 1) <> "." Then strScanSubnet = strScanSubnet & "."
For intNode = strStart To strEnd
	strIPAddress = strScanSubnet & CStr(intNode)
	If Ping(strIPAddress) = True Then
		objOutput.WriteLine """" & strIPAddress & """,""" & GetHostName(strIPAddress) & """,""" & GetCurrentUser(strIPAddress) & """"
	Else
		objOutput.WriteLine """" & strIPAddress & """,""<OFFLINE>"",""<OFFLINE>"""
	End If
Next
objOutput.Close

WScript.Echo "Done. Please see " & strOutputFile

Function GetCurrentUser(strComputer)
	Dim objWMIService, colComputer, objComputer, strUser
	On Error Resume Next
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(Security,Backup)}!\\" & strComputer & "\root\cimv2")
	If Err.Number = 0 Then
		Set colComputer = objWMIService.ExecQuery("Select Username from Win32_ComputerSystem")
		strUser = ""
		For Each objComputer In colComputer
		    strUser = objComputer.UserName
		Next
	End If
	If Err.Number <> 0 Then strUser = "(GetCurrentUser) WMI Error " & Err.Number & ": " & Err.Description
	Err.Clear
	On Error GoTo 0
	GetCurrentUser = strUser
End Function

Function GetHostName(strComputerIP)
	Dim objWMIService, colComputer, objComputer, strComputerName
	On Error Resume Next
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(Security,Backup)}!\\" & strComputerIP & "\root\cimv2")
	If Err.Number = 0 Then
		Set colComputer = objWMIService.ExecQuery("Select Name from Win32_ComputerSystem")
		strComputerName = ""
		For Each objComputer In colComputer
		    strComputerName= objComputer.Name
		Next
	End If
	If Err.Number <> 0 Then strComputerName = "(GetHostName) WMI Error " & Err.Number & ": " & Err.Description
	Err.Clear
	On Error GoTo 0
	GetHostName = strComputerName
End Function

Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
	Else
		Ping = False
	End If
End Function

Open in new window

0
 

Author Comment

by:Bianchi928
ID: 38853400
Just tested the last script. I've pasted part of the report  The OFFLIne is correct..I can't even ping the computer. I can ping all the Error 70 ones as well as all the Error 462 ones.

Very strange.

10.24.20.208      <OFFLINE>      <OFFLINE>
10.24.20.209      (GetHostName) WMI Error 70: Permission denied      (GetCurrentUser) WMI Error 70: Permission denied
10.24.20.210      (GetHostName) WMI Error 70: Permission denied      (GetCurrentUser) WMI Error 70: Permission denied
10.24.20.211      (GetHostName) WMI Error 462: The remote server machine does not exist or is unavailable      (GetCurrentUser) WMI Error 462: The remote server machine does not exist or is unavailable
10.24.20.212      B3YT52S      SPT2000\wgv8071
10.24.20.213      DV59SM1      SPT2000\aa10314
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38853415
Gee....here's another script I use that you can run to test the WMI on one of those machines....just out of curiosity....but it uses the same code anyway.....


Option Explicit
'On Error Resume Next

Dim objShell, objExec, strPingResults, strComputer, objWMIService, colComputer, colComputerIP, colSystemInfo, objComputer, strModel
Dim strUserName, strHostName, IPConfig, intIPCount, strIPAddress, objItem, strOS_Caption, strOS_SPVersion, strOS_VerNumber
 
strComputer = InputBox("Please enter an IP Address or computer name:", _
    "Get User Login Details","172.16.2.64")

If IsEmpty(strComputer) = True Then Wscript.Quit

If Ping(strComputer) = False Then
	MsgBox strComputer & " did not respond to ping. Cannot continue script."
Else

	Set objWMIService = GetObject("winmgmts:" _
	    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
	
	Set colComputer = objWMIService.ExecQuery _
	    ("Select * from Win32_ComputerSystem")
	
	Set colComputerIP = objWMIService.ExecQuery _
	    ("Select * from Win32_NetworkAdapterConfiguration")
	
	Set colSystemInfo = objWMIService.ExecQuery _
	    ("Select * from Win32_OperatingSystem",,48)
	 
	For Each objComputer in colComputer
	    strUserName = "User Name: " & objComputer.UserName
	    strHostName = "Host Name: " & objComputer.Name
	    strModel = "Model: " & objComputer.Model
	Next
	
	For Each IPConfig in colComputerIP
		If Not IsNull(IPConfig.IPAddress) Then 
			'strIPAddress = strIPAddress & IPConfig.Description & ": "
	        For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)
	        	If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" Then
					'strIPAddress = strIPAddress & "IP Address: " & IPConfig.IPAddress(intIPCount) & "~"
					strIPAddress = strIPAddress & IPConfig.IPAddress(intIPCount) & "~"
				End If
			Next
		End If
	Next
	
	If Right(strIPAddress, 1) = "~" Then
		strIPAddress = Left(strIPAddress, Len(strIPAddress) - 1)
	End If
	strIPAddress = Replace(strIPAddress, "~", vbCrLf)
	
	For Each objItem in colSystemInfo
	     strOS_Caption = "Caption: " & objItem.Caption
	     strOS_SPVersion = "SP Version: " & objItem.CSDVersion
	     strOS_VerNumber = "Version Number: " & objItem.Version
	Next
	
	MsgBox strUserName & vbcrlf & strHostName & vbcrlf & _
	     strIPAddress & vbcrlf & strOS_Caption & vbcrlf & _
	     strOS_SPVersion & vbcrlf & strOS_VerNumber & VbCrLf & strModel, vbOKOnly, "Login Details"
End If
     
Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
	Else
		Ping = False
	End If
End Function

Open in new window

0
 

Author Comment

by:Bianchi928
ID: 38853482
Okay..Done the test

On 10.24.20.209, I get Line 16 Permission Denied : 'Get Object' 800A0046
On 10.24.20.210 Same Error message
On 10.24.20.211  Works fine. Gets all the infos


As a reminder I can ping all 3 ip addresses
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38853590
You will get permission denied if the user running the script does not have admin rights to the remote PCs.  Is that the case?
0
 

Author Comment

by:Bianchi928
ID: 38853622
Okay I got someone who has got full admin rights to all remote computers to test it

Result is ;

209 & 210 are fine. Got all infos.
211 comes with "The remote server machine does not exist or is unavailable " "GetObject" Line 16

But when I run 211 I get all infos...

All weird.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38853640
It all seems to suggest that something is a bit off with the WMI of some workstations.  On a problematic one, can you check the troubleshooting steps here:
http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_24109963.html
0
 

Author Comment

by:Bianchi928
ID: 38853653
Rob, I'm very happy with all your efforts. I've got enough scripts to play with now and combinet the infos that I need. I will certainly look into this WMI on some workstations.

Thanks a lot
Cheers
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 38853666
OK, good luck.  Hopefully something comes up that can be resolved.  The script works on my domain, so it should be OK.
0
 

Author Closing Comment

by:Bianchi928
ID: 38853679
You have been so helpful.  I'm learnign a lot.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Companies that have implemented Microsoft’s Active Directory need to ensure that the Active Directory is configured and operating properly. If there are issues found and not resolved, it eventually leads the components to fail or stop working and fi…
Find out how to use Active Directory data for email signature management in Microsoft Exchange and Office 365.
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now