I would like to use a PowerShell script to remove a computer from a Configuration Manager 2012 R2 collection toward the end of a task sequence. I am using invoke-command to run the commands on the remote computer, but one component of the import-module is failing. I can view this when I run this part of the code with the -Verbose switch.
…
#Import SCCM Module
$ModuleName = (get-item $env:SMS_ADMIN_UI_PATH).parent.FullName + “\ConfigurationManager.psd1”
Import-Module $ModuleName -Verbose
…
Here is the error.
VERBOSE: Loading module from path ‘C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\AdminUI.PS.Provider.dll’.
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : InvalidOperation: ( [Import-Module], UnauthorizedAccessException
+ FullyQualifiedErrorId : NewDriveProviderException,Microsoft.PowerShell.Commands.ImportModuleCommand
+ PSComputerName : SERVER
Other dll’s load the other commands without issue. Apparently the AdminUI.PS.Provider.dll provides the ability to CD to the CM site as that essential part of the script also fails.
All of this is contained in an invoke-command scriptblock. Can anyone suggest what this UnautorizedAccessException might indicate? I’ve tried using enable-wsmancredssp on the client and server without benefit.
Here is the complete scrubbed script.
Thank you,
Gary
Capture the hostname of the computer running this script
$ComputerName = hostname
enable-wsmancredssp -role client -delegatecomputer SERVER.DOMAIN.COM -Force
The rest of the script will be executed on SERVER
Invoke-Command -Computer SERVER -ConfigurationName Microsoft.PowerShell32 -Scriptblock{
enable-wsmancredssp -role server -Force
$CollectionIDs = “CM100044;CM100043”
$bEventlogEntry = “1”
$SiteCode = “CM1”
#Import SCCM Module
$ModuleName = (get-item $env:SMS_ADMIN_UI_PATH).parent.FullName + “\ConfigurationManager.psd1”
Import-Module $ModuleName -Verbose
CD $SiteCode":"
#Remove Client from collections
#Get collection id array
$aCollections = ($CollectionIDs).Split(“;”)
#check for each collection if a directmember rule exists, and remove it
foreach($Collection in $aCollections){
If((Get-CMDeviceCollectionDirectMembershipRule -CollectionId $Collection -ResourceName $using:ComputerName).count -eq 1) {
#Write Eventlog entry
If($bEventlogEntry -eq 1){
write-eventlog -logname Application -source “SMS Client” -eventID 3001 -entrytype Information -message “Computer $using:ComputerName will be removed from Collection $Collection” -category 1 -rawdata 10,20
}
#Remove Client from collection
Remove-CMDeviceCollectionDirectMembershipRule -CollectionId $Collection -ResourceName $using:ComputerName -Force
}
}
}