Solved

vbscript returning null username from AD

Posted on 2009-07-08
22
548 Views
Last Modified: 2012-05-08
I have a vbs logon script that should capture the username, hostname & ip address for a user logging on to a windows 2003 network.  The network has 1200+ users and intermittently a script will return one or more null values for the username or host ip address when interogating AD.  There is no consistency that we can see - just a random occurrence.  Code is posted below but if anyone can shed some light on this I would be gratefull
Const ForReading = 1

Const ForWriting = 2 

Const ForAppending = 8

Const ADS_USE_ENCRYPTION = 2

Const ADS_SECURE_AUTHENTICATION = &H1

Const HKEY_CURRENT_USER = &H80000001

Const HKEY_LOCAL_MACHINE = &H80000002
 

Dim objns, objReg, objNetwork, objSysInfo, objNet, PCLog

strComputer = "."
 

'================ Objects 

Set objNetwork = CreateObject("WScript.Network")

Set objSysInfo = CreateObject("ADSystemInfo")

Set objfso = CreateObject("Scripting.FileSystemObject")

set objShell = CreateObject("WScript.Shell") 

Set objNet = CreateObject("WScript.NetWork") 

Set objns = GetObject("LDAP:")

Set objWMIService = GetObject("winmgmts:")

Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
 

strSysRoot = objShell.Environment("PROCESS").Item("SYSTEMROOT")

strAllUsersDesktop = objShell.SpecialFolders("AllUsersDesktop")

strDesktop = objShell.SpecialFolders("Desktop")

strProgramFiles = objShell.Environment("PROCESS").Item("PROGRAMFILES")
 

'================ Variables 

strPCLogPath = "\\DC\logonreport$\PC_Reports\"

strIPLogPath = "\\DC\logonreport$\IP_Reports\"

strUserLogPath = "\\DC\logonreport$\User_Reports\"
 

' Capture the computer name

strComputerName = objNet.ComputerName
 

' Capture the user logon name

On Error Resume Next

    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)

    For Each objItem in colItems

        strCurrentUser = objItem.UserName

Next

' strip domain and get username for file

strUserName = Mid(strCurrentUser,13)
 

' Open the logon report file or create a new one if it does not exist    

If objFSO.FileExists(strPCLogPath & strComputerName & ".txt") Then

	Set PCLog = objFSO.OpenTextFile(strPCLogPath & strComputerName & ".txt", ForAppending, True)

Else

	Set PCLog = objfso.CreateTextFile(strPCLogPath & strComputerName & ".txt", True)

End if
 

' Obtain machine location field from AD

strLocation = GetObjectLocation
 

' Capture IP Address

strIPAddress = GetIPAddress
 

Function GetIPAddress

Set objWMIService = GetObject("winmgmts:" _

    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set IPConfigSet = objWMIService.ExecQuery _

    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

For Each IPConfig in IPConfigSet

    If Not IsNull(IPConfig.IPAddress) Then 

        For i=LBound(IPConfig.IPAddress) to UBound(IPConfig.IPAddress)

            GetIPAddress = IPConfig.IPAddress(i)

        Next

    End If

Next	

End Function

Open in new window

0
Comment
Question by:cmdown
  • 11
  • 11
22 Comments
 
LVL 65

Accepted Solution

by:
RobSampson earned 250 total points
ID: 24803051
Hi, for the username issue, you should be able to change this section:
' Capture the user logon name
On Error Resume Next
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
    For Each objItem in colItems
        strCurrentUser = objItem.UserName
Next
' strip domain and get username for file
strUserName = Mid(strCurrentUser,13)


to just this
strUserName = objNet.UserName

This avoids having to use WMI, which may possibly have a permissions error when querying the Username.

For the IPAddress function, I've modified it slightly, as you can see below.  Perhaps the issue is because you were returning out of the Function before an actual IP Address was found.

Regards,

Rob.
Const ForReading = 1

Const ForWriting = 2 

Const ForAppending = 8

Const ADS_USE_ENCRYPTION = 2

Const ADS_SECURE_AUTHENTICATION = &H1

Const HKEY_CURRENT_USER = &H80000001

Const HKEY_LOCAL_MACHINE = &H80000002

 

Dim objns, objReg, objNetwork, objSysInfo, objNet, PCLog

strComputer = "."

 

'================ Objects 

Set objNetwork = CreateObject("WScript.Network")

Set objSysInfo = CreateObject("ADSystemInfo")

Set objfso = CreateObject("Scripting.FileSystemObject")

set objShell = CreateObject("WScript.Shell") 

Set objNet = CreateObject("WScript.NetWork") 

Set objns = GetObject("LDAP:")

Set objWMIService = GetObject("winmgmts:")

Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")

 

strSysRoot = objShell.Environment("PROCESS").Item("SYSTEMROOT")

strAllUsersDesktop = objShell.SpecialFolders("AllUsersDesktop")

strDesktop = objShell.SpecialFolders("Desktop")

strProgramFiles = objShell.Environment("PROCESS").Item("PROGRAMFILES")

 

'================ Variables 

strPCLogPath = "\\DC\logonreport$\PC_Reports\"

strIPLogPath = "\\DC\logonreport$\IP_Reports\"

strUserLogPath = "\\DC\logonreport$\User_Reports\"

 

' Capture the computer name

strComputerName = objNet.ComputerName

 

' Capture the user logon name

'On Error Resume Next

'    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)

'    For Each objItem in colItems

'        strCurrentUser = objItem.UserName

'Next

' strip domain and get username for file

'strUserName = Mid(strCurrentUser,13)

strUserName = objNet.UserName
 

' Open the logon report file or create a new one if it does not exist    

If objFSO.FileExists(strPCLogPath & strComputerName & ".txt") Then

	Set PCLog = objFSO.OpenTextFile(strPCLogPath & strComputerName & ".txt", ForAppending, True)

Else

	Set PCLog = objfso.CreateTextFile(strPCLogPath & strComputerName & ".txt", True)

End if

 

' Obtain machine location field from AD

strLocation = GetObjectLocation

 

' Capture IP Address

strIPAddress = GetIPAddress

 

Function GetIPAddress

	Set objWMIService = GetObject("winmgmts:" _

	    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

	Set IPConfig = objWMIService.ExecQuery _

	    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

	strIPAddress = ""

	For Each IPConfig in colComputerIP

		If Not IsNull(IPConfig.IPAddress) Then 

			For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)

				If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" Then strIPAddress = IPConfig.IPAddress(intIPCount)

			Next

		End If

	Next

	GetIPAddress = strIPAddress

End Function

Open in new window

0
 
LVL 1

Author Comment

by:cmdown
ID: 24805671
Hi Rob

Thanks for the reply.  The revised IP code returns an error - object not a collection for line
For Each IPConfig in colComputerIP
How should the collection be defined ? - Dim colComputerIP As New Collection.  Is anything else required ?
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 24809663
Oh whoops, copy and paste error from some of my other code....This:
      Set IPConfig = objWMIService.ExecQuery _

should have been:
      Set colComputerIP = objWMIService.ExecQuery _

Regards,

Rob.
Const ForReading = 1

Const ForWriting = 2 

Const ForAppending = 8

Const ADS_USE_ENCRYPTION = 2

Const ADS_SECURE_AUTHENTICATION = &H1

Const HKEY_CURRENT_USER = &H80000001

Const HKEY_LOCAL_MACHINE = &H80000002

 

Dim objns, objReg, objNetwork, objSysInfo, objNet, PCLog

strComputer = "."

 

'================ Objects 

Set objNetwork = CreateObject("WScript.Network")

Set objSysInfo = CreateObject("ADSystemInfo")

Set objfso = CreateObject("Scripting.FileSystemObject")

set objShell = CreateObject("WScript.Shell") 

Set objNet = CreateObject("WScript.NetWork") 

Set objns = GetObject("LDAP:")

Set objWMIService = GetObject("winmgmts:")

Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")

 

strSysRoot = objShell.Environment("PROCESS").Item("SYSTEMROOT")

strAllUsersDesktop = objShell.SpecialFolders("AllUsersDesktop")

strDesktop = objShell.SpecialFolders("Desktop")

strProgramFiles = objShell.Environment("PROCESS").Item("PROGRAMFILES")

 

'================ Variables 

strPCLogPath = "\\DC\logonreport$\PC_Reports\"

strIPLogPath = "\\DC\logonreport$\IP_Reports\"

strUserLogPath = "\\DC\logonreport$\User_Reports\"

 

' Capture the computer name

strComputerName = objNet.ComputerName

 

' Capture the user logon name

'On Error Resume Next

'    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)

'    For Each objItem in colItems

'        strCurrentUser = objItem.UserName

'Next

' strip domain and get username for file

'strUserName = Mid(strCurrentUser,13)

strUserName = objNet.UserName

 

' Open the logon report file or create a new one if it does not exist    

If objFSO.FileExists(strPCLogPath & strComputerName & ".txt") Then

	Set PCLog = objFSO.OpenTextFile(strPCLogPath & strComputerName & ".txt", ForAppending, True)

Else

	Set PCLog = objfso.CreateTextFile(strPCLogPath & strComputerName & ".txt", True)

End if

 

' Obtain machine location field from AD

strLocation = GetObjectLocation

 

' Capture IP Address

strIPAddress = GetIPAddress

 

Function GetIPAddress

	Set objWMIService = GetObject("winmgmts:" _

	    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

	Set colComputerIP = objWMIService.ExecQuery _

	    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

	strIPAddress = ""

	For Each IPConfig in colComputerIP

		If Not IsNull(IPConfig.IPAddress) Then 

			For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)

				If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" Then strIPAddress = IPConfig.IPAddress(intIPCount)

			Next

		End If

	Next

	GetIPAddress = strIPAddress

End Function

Open in new window

0
 
LVL 1

Author Comment

by:cmdown
ID: 24814596
Thanks Rob
That's going through.  Should find out in next 24 hours if it has resolved the problem.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 24819708
No problem. Hopefully it's OK.

Rob.
0
 
LVL 1

Author Comment

by:cmdown
ID: 24825819
hi Rob
Sorry to say that I'm still getting null values returned - IP as 0.0.0.0 and username as "".  These values are set when the variables are declared at the start of the script but the respective functions clear these values before searching the AD records.  Could the function fail to call for any reason ?
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 24828399
Hey wait a second....Am I missing some code?  I'm missing a GetObjectLocation function, and also missing any code that writes output to the file......

Did I miss that?  Are you able to post the code for me to look at?

Regards,

Rob.
0
 
LVL 1

Author Comment

by:cmdown
ID: 24971523
Hi Rob
Sorry for the delay - been away on holiday.  I'll upload the full script when I'm back in the office tomorrow.
Regards, Chris
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 25012345
Hi Chris, any update on this?

Regards,

Rob.
0
 
LVL 1

Author Comment

by:cmdown
ID: 25013704
Hi Rob
Sorry - been off until today.  Full script attached - anonymised.
Could I be very cheeky and ask you if youy would mind also having a look at a question I've posted today (Q_24624505) as this also requires a vbscript solution.
Regards
Chris
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 25019365
Hi, I can't seem to find the script.....

Hopefully I'm not going blind....

Rob.
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 1

Author Comment

by:cmdown
ID: 25021490
Right ... EE is looking inside the zip and not allowing vbs upload  - I must have missed the warning message yesterday!  Renamed to .txt and attached herewith.
 
 

EElogon.vbs.txt.zip
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 25029797
OK, I'll test this out tomorrow....
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 25040379
Hmmm, maybe we'll have to break it down a bit.  Try just this code, and type in one of those machines that is reporting a 0.0.0.0

The script should retrieve all valid IPs assigned to a machine.

Regards,

Rob.
Dim strComputer

strComputer = InputBox("Enter computer name to retrieve IP Address:", "Computer Name")

MsgBox GetIPAddress
 

' revised GetIPAddress Function

Function GetIPAddress

	Set objWMIService = GetObject("winmgmts:" _

	    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

	'Set IPConfig = objWMIService.ExecQuery _

	Set colComputerIP = objWMIService.ExecQuery _

	    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

	strIPAddress = ""

	For Each IPConfig in colComputerIP

		If Not IsNull(IPConfig.IPAddress) Then 

			For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)

				If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" Then

					If strIPAddress = "" Then

						strIPAddress = IPConfig.IPAddress(intIPCount)

					Else

						strIPAddress = strIPAddress & VbCrLf & IPConfig.IPAddress(intIPCount)

					End If

				End If

			Next

		End If

	Next

	GetIPAddress = strIPAddress

End Function

Open in new window

0
 
LVL 1

Author Comment

by:cmdown
ID: 25041413
Hi Rob
Thanks for this. Needless to say the ones that regularly report this issue are turned off at the moment. As these machines are in a school that is mostly closed for the summer holidays it may be a while until I can locate or get access to them.  Can we put this Q on hold until I get back in touch ?
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 25056483
We can't really put it on hold, as the cleanup process will probably close it after a month or so with no activity, but if we let it close out, you can still post comments on it, at which time you can post a new question, and post the link to it here, so that I see it.

No hurry, see how you go.

Regards,

Rob.
0
 
LVL 1

Author Comment

by:cmdown
ID: 25369525
hi Rob
I'm still looking into this - although I've been off for a few days and come back to a conficker infestation - so much for wsus !
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 25379772
Oh bugger!  Good luck with that....wsus won't do the full job, you'll need some anti-virus protection too, but I'm sure you have that...

No problem. Take your time.

Regards,

Rob.
0
 
LVL 1

Author Comment

by:cmdown
ID: 25504076
Hi Rob
I think we're on top of the outbreak now.  I'll try and have another look at this tomorrow.
Regards
Chris
 
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 25510260
Sure, no worries. Thanks for the update.

Rob.
0
 
LVL 1

Author Comment

by:cmdown
ID: 25741252
Hi Rob
I think the null IP issue is sorted now thanks to your fix.  Just checking on the null usernames.
0
 
LVL 1

Author Closing Comment

by:cmdown
ID: 31656087
Thanks Rob.  I've been off unwell but I'm please to say that having incorporated your script modification into our logoff script as well we've not had any null username or IP details returned since 2nd Nov.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction You may have a need to setup a group of users to allow local administrative access on workstations.  In a domain environment this can easily be achieved with Restricted Groups and Group Policies. This article will demonstrate how to…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
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 transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…

863 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

22 Experts available now in Live!

Get 1:1 Help Now