I have a script that previously worked in PSU, but since transitioning to an Integrated environment (and not using Run-As accounts for everything), I’m getting the below error:
The error occurs when trying to run “Get-CASMailbox” or “Get-DistributionGroupMember”. I am at a loss because I can run this script as-is outside of PSU and it worked previously when running the AppPool as “SYSTEM” and using a Run-As account. I’m now using a service account (e.g. “PSUSvc”) and using that account the script runs fine in an interactive PowerShell session (both v5.1 and v7.2), but within PSU I get the “Object reference not set to an instance of an object” error every time.
Here is a sanitized version of the script:
# Set ActiveSync Status
Try{
$Params = @{
ConfigurationName = "Microsoft.Exchange"
ConnectionUri = "http://exchsrvr.contoso.com/PowerShell/?SerializationLevel=Full"
}
$Session = New-PSSession @Params -ErrorAction Stop
$failed = $false
} Catch {
Write-Error "ERROR in $($MyInvocation.MyCommand) on line $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)"
$failed = $true
Break
}
$Commands = "Get-DistributionGroupMember","Get-CasMailbox","Set-CASMailbox"
$SessionParams = @{
Session = $Session
CommandName = $Commands
FormatType = "*"
DisableNameChecking = $True
AllowClobber = $True
}
Import-PSSession @SessionParams | Out-Null
If ($failed -eq $false) {
$ActiveSyncGroup = '<Name of Custom Group>'
Try{
$AllCAS = Get-CASMailbox -ResultSize Unlimited -ErrorAction Stop ## This is the command that fails ##
$HashLookup = @{}
$AllCAS.ForEach({$HashLookup.Add($_.Name,$_.ActiveSyncEnabled)})
} Catch {
Write-Error "ERROR in $($MyInvocation.MyCommand) on line $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)"
}
Try{
$GroupUsers = Get-DistributionGroupMember $ActiveSyncGroup -ResultSize Unlimited -ErrorAction Stop ## This command also fails ##
} Catch {
Write-Error "ERROR in $($MyInvocation.MyCommand) on line $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)"
Break
}
Foreach($Entry in $AllCAS){
If(($Entry.SamAccountName -notin $GroupUsers.SamAccountName) -and ($HashLookup["$($Entry.SamAccountName)"])){
Set-CASMailbox -Identity $Entry.PrimarySmtpAddress -ActiveSyncEnabled $false # Disable ActiveSync
} Elseif (($Entry.SamAccountName -in $GroupUsers.SamAccountName) -and (-Not($HashLookup["$($Entry.SamAccountName)"]))){
Set-CASMailbox -Identity $Entry.PrimarySmtpAddress -ActiveSyncEnabled $true # Enable ActiveSync
}
}
} Else {
Write-Information "ERROR getting credential or accessing Exchange server"
}
Remove-PSSession $Session # Cleanup session after run
Any thoughts?
Product: PowerShell Universal
Version: 2.8.1