3

#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
Filed in: Columns, Tips and Tricks Tags: , ,

3 Responses to "#PSTip Get the AD site name of a computer"

  1. Peter says:

    I’m trying to create a script that determines the site of a remote, offline computer. I want to send messages to admins on site about that they forgot to move the computer object to appropriate OU and they left it in the default Computers OU.
    These objects mostly offline computers but I can query their IPv4Address property so I can search for the ADSite based on subnet.

Leave a Reply

Submit Comment

© 2017 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: