Function to Connect to Configuration Manager Site Using PowerShell

When trying to connect to your ConfigMgr Site using PowerShell, sometimes the connection attempt may fail. I’ve found this to be the case more in automation scripts running in a Task Sequence than ones that run locally on the Site Server, but still, something had to be done.

To ensure a successful connection, I came up with the following function to give us a better chance of success and this has been working quite well for us in our Task Sequence scripts.

Notice the Do Until loop.  During TS execution the remote connect to our CAS may fail on the first couple of attempts.  Adding the Do Until loop allows us to try multiple times and in those instances where we don’t connect on the first try, we usually do by the second or third.

Hope this helps!

Function Connect-CMSite {
   $SiteCode = $CASSiteCode
   $SiteServer = $CASSiteServer

   Import-Module $env:SMS_ADMIN_UI_PATH.Replace("\bin\i386", "\bin\ConfigurationManager.psd1")
   $CMDrive = Get-PSDrive -Name $SiteCode -ErrorAction Ignore

   # Connect to CMDrive
   if ($CMDrive) {
      Write-Host "PSDrive: $SiteCode already exists, changing current drive"
      Set-Location $SiteCode":"
   }
   else {
      Write-Host "PSDrive: $SiteCode does not exist, adding..."
      $i = 1

      Do {
         Write-Host "Loop $i"
         $NewDrive = New-PSDrive -Name $SiteCode -PSProvider "CMSite" -Root $SiteServer -Scope Global
         $i++
      } Until ($NewDrive -ne $null -or $i -gt 10)

      Set-Location $SiteCode":"
   }
}

1 thought on “Function to Connect to Configuration Manager Site Using PowerShell”

Leave a Reply to Joe Cancel reply