Running SCCM commands remotely

There are a lot of different ways I see people connect to SCCM to run commands remotely, however in my environment I had mixed results with those techniques. Sometimes the command worked fine, and other times during loading of the module, not all components of the module loaded properly even though it showed it did. I’m not sure if this was a glitch within SCCM or my environment, but I ended up figuring out a fail-safe way to load the module for my needs and it has worked for me all the time.

$SCCMServer = "SCCMServer"
$SessionsRunning = get-pssession

#Create a new Session to the SCCM Server
if(!($SessionsRunning.ComputerName -like $SCCMServer) -and ($env:COMPUTERNAME -ne $SCCMServer))
{
	$Session = New-PSSession -ComputerName $SCCMServer -Authentication Kerberos
}

#=================== Invoke the command(s) within the context of our SCCM Server

Invoke-Command -Session $Session -ScriptBlock {

	#Get Site Code & Path
	[string]$SiteCode = (((Get-WmiObject -Namespace "root\SMS" -Class "SMS_ProviderLocation") | Select-Object | Where-Object { $_.__RELPATH -like "*$env:COMPUTERNAME*"}) | Select-Object -ExpandProperty SiteCode)
	[string]$SitePath = $SiteCode + ":"
   
	#Import our Module. If it fails loading, it will loop and try to reload until it succeeds.
	While($True)
	{
		CLS
		Try
		{
			Import-Module (Join-Path (Split-Path $env:SMS_ADMIN_UI_PATH) "ConfigurationManager.psd1") -Force  -ErrorAction Stop #-Verbose
			Break
		}
		Catch
		{
			(Get-Module -Name "ConfigurationManager") | Remove-Module
			Start-Sleep -Milliseconds 100
		}
	}
    
	#If the module is imported without any issues, but we don't have a drive mapped, check to see if the provider is available
	if($NULL -eq ((Get-PSDrive -ErrorAction SilentlyContinue) | Select-Object | Where-Object { $_.Provider -like "*CMSite*" }))
	{
		#Get-PSProvider
		((Get-PSProvider -ErrorAction SilentlyContinue) | Select-Object | Where-Object { $_.name -like "*CMSite*" }) | fl *

		#Create the Drive
		Try
		{
			New-PSDrive -Name $SiteCode -PSProvider "AdminUI.PS\CMSite" -Root "$ENV:COMPUTERNAME" -Description "SCCM Primary Site" -ErrorAction Stop
		}
		Catch
		{
			Write-Error $_.Exception
		}
	}
	
	#Set our Path to the CMSite
	if((Get-Location -ErrorAction SilentlyContinue).Path -ne $($SitePath + "\"))
	{
		Set-location $sitepath
	}
	
	#===================
	
	#Now you can start your main SCCM code here
}