Gather SCCM Site Code – PowerShell

During a recent ConfigMgr side by side migration project I was asked to provide a reliable way to return AD Site and SCCM site code information for each computer in an OU. The below PowerShell script is what i came up with.


$result = @()
$time = 1
$searchbase = 'OU=WORKSTATIONS,DC=COMPANY,DC=com'
$list = (Get-ADComputer SearchBase $searchbase Filter 'Enabled -eq $true').name
function Get-ComputerSite($i)
{
$site = nltest /server:$i /dsgetsite 2>$null
if($LASTEXITCODE -eq 0){ $site[0] }
}
Foreach ($i in $list)
{
$resData = New-Object System.Object
$resData | Add-Member type NoteProperty name ComputerName value $i
if (Test-Connection ComputerName $i Quiet Count 1)
{
try {
$resData | Add-Member type NoteProperty name SiteCode value ((Invoke-WMIMethod ComputerName $i –Namespace root\ccm –Class SMS_Client –Name GetAssignedSite ErrorAction Stop).sSiteCode)
$resData | Add-Member type NoteProperty name ADSite value (Get-ComputerSite $i) }
catch {$resData | Add-Member type NoteProperty name SiteCode value ("Connection Failed : $($error[0].Exception.Message)") Force}
}
else {$resData | Add-Member type NoteProperty name SiteCode value ('Connection Failed : Ping Failed')}
$result += $resData
Write-Progress activity "Checking Site Codes for $($list.length) clients" status "Percent checked: " PercentComplete (($time / $list.length) * 100)
$time++
}
$result | sort SiteCode

The script will return Name, ADSite and SCCM site code information for each computer within the Active Directory OU defined in the variable ‘$searchbase’ .

As the ‘Invoke-WMIMethod’ method has no reliable way to timeout quickly, i first test connectivity to each machine with a simple 1 packet ping (Test-Connection ComputerName $i Quiet Count 1) if the ping fails, it will not attempt a WMI connection.

A progress bar will track and show computer counts, finally results including error codes are stored in the $result variable.

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s