Connect to SCCM Site with PowerShell

This script snippet can be used at the beginning of a script to dynamically find SCCM sites and then change directory to an SCCM CAS site, after which scripts can be run using SCCM cmdlets.

$PathToInstall = #YourPathHere
if (!(test-path ("C:\Program Files (x86)\ConfigMgrConsole\bin\ConfigurationManager.psd1")))
{
$Install = Read-host "No Configuration Manager commandlet installed. Would you like to install?[Y/N]"
    if ($Install -eq "Y")
    {
        #Install tools if desired
        start-process msiexec.exe -argumentlist "/i $PathToInstall /q" -Wait
    }
    else
    {
        #Exits script, as this won't work without SCCM module
        Write-host "No Commandlets found, exiting script"
        pause
        exit
    }

}
#Import modules for AD and SCCM from the start
import-module ActiveDirectory
import-module ConfigurationManager

# (optional) Dynamically retrieve the domain root distinguished name
$DomainRoot = ([adsi]"").distinguishedName

# (optional) Get ADSI object to represent search root
$SearchRoot = [adsi]("LDAP://CN=System Management,CN=System," + $DomainRoot)

# Create an ADSI searcher object, with LDAP-style search filter syntax
$AdSearcher = [adsisearcher]"(objectClass=mSSMSSite)"

# (optional) Set search root of Active Directory searcher to System Management container
$AdSearcher.SearchRoot = $SearchRoot

# Make call to retrieve objects from Active Directory
$SccmSites = $AdSearcher.FindAll()

# Iterate over each mSSMSSite object, and give me the mssmssitecode property
# IMPORTANT: All Active Directory property references must be in lower-case, else ... fail
$SCCMSiteCodes = foreach ($SccmSite in $SccmSites)
{
    $SccmSite.Properties["mssmssitecode"]
}

#Go through every site code in environment to try and connect to Central Admin site
foreach ($siteCode in $SCCMSiteCodes){
Write-host "Changing Directory to $Sitecode`:"
try
{
#If change directory is successful, break from script. If not, go to catch
cd $siteCode`: -ErrorAction Stop
break
}
catch
{
Write-Warning "$sitecode directory does not work"
}
}

Comments

Popular posts from this blog

Application Doesn't Install During OSD Task Sequence in SCCM

SCCM PXE Boot Issues - No Advertisements Found

Outlook VBA Macros for Journal Entries