#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.

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

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
Default-First-Site-Name
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

Default-First-Site-Name
Share on: