• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1264
  • Last Modified:

VBScript Query Local Unit for IP Subnet / related AD Logon Server?


In an off-the-wall question...  Is it possible to have a vbscript query the local machine's IP address and compare the value against AD sites and services - with the environmental variable %logonserver% to see if it's being serviced by the correct logon server.

This is of course a direct attempt to ~NOT~ have to log in manually to a machine and type "echo %LOGONSERVER%"

If this is at all possible, a script that could be run against the local machine would be more than appreciated, as I would then modify it for a login-script for our purposes.  (We're going to be implementing some basic printer mapping / etc. based off of this information).

Any information that can be provided would be greatly appreciated.
  • 3
  • 2
  • 2
3 Solutions
x-menIT super heroCommented:
On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_NetworkLoginProfile")
For Each objItem in colItems
    Wscript.Echo "Logon Server: " & objItem.LogonServer
x-menIT super heroCommented:
the whole shebang:

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_NetworkLoginProfile")

For Each objItem in colItems
    dtmWMIDate = objItem.AccountExpires
    strReturn = WMIDateStringToDate(dtmWMIDate)
    Wscript.Echo "Account Expires: " & strReturn
    Wscript.Echo "Authorization Flags: " & objItem.AuthorizationFlags
    Wscript.Echo "Bad Password Count: " & objItem.BadPasswordCount
    Wscript.Echo "Caption: " & objItem.Caption
    Wscript.Echo "CodePage: " & objItem.CodePage
    Wscript.Echo "Comment: " & objItem.Comment
    Wscript.Echo "Country Code: " & objItem.CountryCode
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo "Flags: " & objItem.Flags
    Wscript.Echo "Full Name: " & objItem.FullName
    Wscript.Echo "Home Directory: " & objItem.HomeDirectory
    Wscript.Echo "Home Directory Drive: " & objItem.HomeDirectoryDrive
    dtmWMIDate = objItem.LastLogoff
    strReturn = WMIDateStringToDate(dtmWMIDate)
    Wscript.Echo "Last Logoff: " & strReturn
    dtmWMIDate = objItem.LastLogon
    strReturn = WMIDateStringToDate(dtmWMIDate)
    Wscript.Echo "Last Logon: " & strReturn
    Wscript.Echo "Logon Hours: " & objItem.LogonHours
    Wscript.Echo "Logon Server: " & objItem.LogonServer
    Wscript.Echo "Maximum Storage: " & objItem.MaximumStorage
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Number Of Logons: " & objItem.NumberOfLogons
    Wscript.Echo "Password Age: " & objItem.PasswordAge
    dtmWMIDate = objItem.PasswordExpires
    strReturn = WMIDateStringToDate(dtmWMIDate)
    Wscript.Echo "Password Expires: " & strReturn
    Wscript.Echo "Primary Group ID: " & objItem.PrimaryGroupId
    Wscript.Echo "Privileges: " & objItem.Privileges
    Wscript.Echo "Profile: " & objItem.Profile
    Wscript.Echo "Script Path: " & objItem.ScriptPath
    Wscript.Echo "Setting ID: " & objItem.SettingID
    Wscript.Echo "Units Per Week: " & objItem.UnitsPerWeek
    Wscript.Echo "User Comment: " & objItem.UserComment
    Wscript.Echo "User Id: " & objItem.UserId
    Wscript.Echo "User Type: " & objItem.UserType
    Wscript.Echo "Workstations: " & objItem.Workstations
Function WMIDateStringToDate(dtmWMIDate)
    If Not IsNull(dtmWMIDate) Then
    WMIDateStringToDate = CDate(Mid(dtmWMIDate, 5, 2) & "/" & _
         Mid(dtmWMIDate, 7, 2) & "/" & Left(dtmWMIDate, 4) _
             & " " & Mid (dtmWMIDate, 9, 2) & ":" & _
                 Mid(dtmWMIDate, 11, 2) & ":" & Mid(dtmWMIDate, 13, 2))
    End If
End Function

Open in new window

usslindstromAuthor Commented:
You are absolutely amazing!

Thank you so much for this information / script...

When I'm running it though, the echo's are only returning the "quoted string" and null values for all the objects.

Would you happen to know how I can resolve that?  I assumed it was admin privileges, but even with a full-on admin rights account it returns just nulls.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

x-menIT super heroCommented:
remove the first line (ON ERROR RESUME NEXT) so the script wil breack on the first error to troubleshoot.

I run it as a local admin and it works fine.
Chris DentPowerShell DeveloperCommented:
This is something I've done before, but I'm afraid it's quite a long time since I stopped doing stuff in VbScript. This script does the following:

1. Reads site configuration from AD
2. Reads computers from AD
3. Connects to the computer and pulls local network configuration
4. Figures out which site the computer should belong to (based on IP config)
5. Reports current site (taken from registry on the computer)
6. Reports logon server (as close as we can get, it's user-specific and that's hard to get to otherwise)

It requires:

Quest AD CmdLets: http://www.quest.com/powershell/activeroles-server.aspx
NetShell (for subnet math functions): http://www.indented.co.uk/index.php/2010/11/25/netshell/

Which probably makes it quite a lot more work than you wanted, but I don't want to rewrite it in VbScript, so I figure it's worth posting just in case.

Function Get-RegistryValue {
      Gets an arbitrary registry value.
      Get-RegistryValue attempts to read the specified values from the registry.
    .Parameter Key
      A registry key relative to the Hive.
    .Parameter Name
      Specifies the name of the registry value.
    .Parameter Hive
      The Registry Hive to add the key to. The default value is LocalMachine.
    .Parameter Computer
      The target system, by default the value is read from the local machine.
    .Parameter StartRemoteRegistry
      The script should attempt to start the remote registry service if it is not already running. 
      This parameter will only take effect if the service is not disabled.

    [Parameter(Mandatory = $True, Position = 0, HelpMessage = "Enter a registry key (relative to Hive)")]
    [Parameter(Mandatory = $True, Position = 1, HelpMessage = "Enter a value name")]
    [Microsoft.Win32.RegistryHive]$Hive = "LocalMachine",
    [String]$ComputerName = $Env:ComputerName,

  If ($StartRemoteRegistry) {
    $ShouldStop = $False
    $Service = Get-WmiObject Win32_Service -Filter "Name='RemoteRegistry'" -Computer $ComputerName
    If ($Service.State -eq "Stopped" -And $Service.StartMode -ne "Disabled") {
      $ShouldStop = $True
      $Service.StartService() | Out-Null

  $BaseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $ComputerName)

  If ($BaseKey -ne $Null) {
    $RegistryKey = $BaseKey.OpenSubKey($Key)

  If ($StartRemoteRegistry -And $ShouldStop) {
    $Service.StopService() | Out-Null

Add-PsSnapIn Quest.ActiveRoles.ADManagement
Import-Module NetShell

$Sites = Get-QADObject -Type subnet -SearchRoot (([ADSI]"LDAP://RootDSE").Get("configurationNamingContext")) `
    -IncludedProperties siteObject | 
  Select-Object Name, 
    @{n='Site';e={ ([ADSI]"LDAP://$($_.siteObject)").Get("name") }},
    @{n='SiteNetworkAddress';e={ $_.Name -Replace '/.*$' }},
    @{n='SiteMaskLength';e={ $_.Name -Replace '^[\d\.]*/' }}

Get-QADComputer -OperatingSystem * | Where-Object { Test-Connection $_.DnsHostName -Quiet -Count 1 } | ForEach-Object {
  $Computer = $_

  $Adapter = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter "IPEnabled=$True" -Computer $Computer.DnsHostName |
    Where-Object { $_.DefaultIPGateway }

  $Adapter | Select-Object `
    @{n='ComputerName';e={ $Computer.Name }},
    @{n='DN';e={ $Computer.DN }},
      $IPAddress = $_.IPAddress; $IPSubnet = $_.IPSubnet
      $( For ($i = 0; $i -lt $IPAddress.Count; $i++) {
        If (([Net.IPAddress]($IPAddress[$i])).AddressFamily -eq "InterNetwork") {
          $ClientNetworkAddress = Get-NetworkAddress $IPAddress[$i] $IPSubnet[$i]
          $ClientMaskLength = ConvertTo-MaskLength $IPSubnet[$i]

          $Sites | 
            Where-Object { $_.SiteNetworkAddress -eq $ClientNetworkAddress -And $_.SiteMaskLength -eq $ClientMaskLength } |
            Select-Object -ExpandProperty Site
      } ) }},
    @{n='ComputerSite';e={ Get-RegistryValue -Key "Software\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine" `
      -Name "Site-Name" -Computer $Computer.DnsHostName -StartRemoteRegistry }},
    @{n='LogonServer';e={ Get-RegistryValue -Key "Software\Microsoft\Windows\CurrentVersion\Group Policy\History" `
      -Name "DCName" -Computer $Computer.DnsHostName -StartRemoteRegistry }}

Open in new window

usslindstromAuthor Commented:
Thank you for both your answers guys.

I wasn't able to get that code as is working x-men - but it's 100% due to my non-programming mentality.  I removed the explicit option at the top, but I still got null values using that code...  BUUUUUT - I borrowed what you just gave me and adapted it to a script that I do have that works for what I was needing,  Much appreciated.

Chris-Dent - Thank you for the PowerShell..I'll keep that in mind as I start to transition to the newer stuff, but as this was for a logon script for XP, I'm gonna' keep it to vb for now and get on with PowerShell once we start adopting Win7 in our environment.

Thanks guys.
Chris DentPowerShell DeveloperCommented:
If you're using it in a Logon Script, you can get the current site name like this (if it's any help):
Set objADSysInfo = CreateObject("ADSystemInfo")
strSiteName = objADSysInfo.SiteName

Open in new window

Which may help if it comes to a comparison with the Logon Server variable.


Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now