Search code examples
powershellactive-directory

Best PowerShell method to get the current Active Directory Site name of the local computer


What are the different ways to get the current Active Directory (AD) site in PowerShell - and which is the fastest, most efficient, and works under the most scenarios?


Solution

  • There are a number of methods available:

    1. Using the nltest.exe command line tool - does not generate network traffic, returns the previous AD site even when offline, but because you are shelling out to a command it is slow, and you need to make sure you test $LASTERRORCODE afterwards in case of errors:

    (& "$env:SystemRoot\System32\nltest.exe" /DSGETSITE)[0]

    1. Using .NET - faster, and useful if you need the full site information as well as the name - however please note that any calls using this .NET class generates traffic to your local domain controller:

    [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Name

    1. Using the registry (Netlogon key) - does not generate network traffic, fast, but be aware that sometimes on domain controllers this value does not exist or may be incorrect:

    (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters').DynamicSiteName

    1. Using the registry (Group Policy key) - does not generate network traffic, fast, works even on domain controllers, but only updates after a successful Group Policy refresh (by default takes up to 90 minutes):

    (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine').'Site-Name'

    1. Using WMI to access the Win32_NTDomain class - don't do this - it is super slow, as well as generating network traffic every time you run it:

    (Get-CimInstance -ClassName Win32_NTDomain -Filter 'DomainControllerName != NULL' -Property ClientSiteName).ClientSiteName

    1. (My personal favourite) Using the AdSystemInfo COM object - does not generate network traffic, will throw normal PowerShell errors without additional error handling, works on all devices, and fast.

    [__ComObject].InvokeMember('SiteName', 'GetProperty', $null, (New-Object -ComObject ADSystemInfo), $null)

    Options 1-3: https://powershellmagazine.com/2013/04/23/pstip-get-the-ad-site-name-of-a-computer/

    Option 4: https://www.powershellgallery.com/packages/Get-ADSiteName/1.0/Content/Get-ADSiteName.ps1

    Option 5: https://www.reddit.com/r/PowerShell/comments/4cjdk8/get_the_ad_site_name_of_a_computer/

    Option 6: https://learn.microsoft.com/en-us/windows/win32/adsi/iadsadsysteminfo-property-methods