Sunday, November 8, 2009

How to get SCCM site code using Powershell

I spent quite some time scripting SCCM using Powershell – I plan to write some blog post about what I have done, because it is probably most complex scripted solution I ever wrote, but for now, I would like to share one trick with you.

When you script SCCM, you do it through WMI classes. SCCM classes are however not stored in default namespace – therefore whenever you want to access SCCM, you need code that looks similar to below:

Get-WmiObject –ComputerName “ServerX” –NameSpace “Root\SMS\Site_<YouSite> –Class …

Which means that for every script you should accept at least arguments –ComputerName and –SiteCode, which can be pretty annoying to type over and over again. Therefore I use following trick to get sitecode automatically:

# Specify one of SCCM servers and Site code is returned automatically
Function Global:SCCM\Get-Site([string]$ComputerName = $(Throw "Required parameter -ComputerName was not specified in SCCM\Get-Site function")) {
    get-WMIObject -ComputerName $ComputerName -Namespace "root\SMS" -Class "SMS_ProviderLocation" | foreach-object{
        if ($_.ProviderForLocalSite -eq $true){$SiteCode=$_.sitecode}
    if ($SiteCode -eq "") {
        throw ("Sitecode of ConfigMgr Site at " + $ComputerName + " could not be determined.")
    } else {
        Return $SiteCode


Jordan said...

I'm looking to query the SCCM database to get the MAC address for a PC that I know the name of. Can I do this in powershell? have you done something similar? any help much appreciated

SEO Services said...

really useful, keep posting

sudhakar said...

I am new to PowerShell. Where should I give machine name??