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

Posted on 2011-05-05
Last Modified: 2012-05-11

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.
Question by:usslindstrom
    LVL 18

    Accepted Solution

    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
    LVL 18

    Assisted Solution

    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

    LVL 5

    Author Comment

    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.
    LVL 18

    Expert Comment

    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.
    LVL 70

    Assisted Solution

    by:Chris Dent
    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:
    NetShell (for subnet math functions):

    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

    LVL 5

    Author Closing Comment

    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.
    LVL 70

    Expert Comment

    by:Chris Dent
    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

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Mapping Drives using Group policy preferences Are you still using old scripts to map your network drives if so this article will show you how to get away for old scripts and move toward Group Policy Preference for mapping them. First things f…
    Over the years I have built up my own little library of code snippets that I refer to when programming or writing a script.  Many of these have come from the web or adaptations from snippets I find on the Web.  Periodically I add to them when I come…
    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 from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…
    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 …

    746 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

    20 Experts available now in Live!

    Get 1:1 Help Now