#PSTip Get the AD site name of a computer

There are a few ways to get the site a computer is a member of. In .NET we can use the ActiveDirectorySite class.


This can be extremly usefull if you want to base a script on the value of the computer’s site. Sometimes, however, you’ll want to query the site of remote computer. Unfortunately, the ActiveDirectorySite class doesn’t allow that. One way to get the information is to query the DynamicSiteName registry value of the remote machine. The current site information is cached in the registry of a given machine under (HKLM:\SYSTEM\CurrentControlSet\services\Netlogon\Parameters).

Another way would be using the nltest command line utility

PS> nltest /server:server1 /dsgetsite
The command completed successfully

If the command completed successfully, we’ll have the site name in the first line. The last step is to wrap this into a function so we can reuse it later on.

function Get-ComputerSite($ComputerName)
	$site = nltest /server:$ComputerName /dsgetsite 2>$null
	if($LASTEXITCODE -eq 0){ $site[0] }

PS> Get-ComputerSite server1


About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts