Object reference not set to an instance of an object

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

Can you try to catch the exception and get a stack trace? It might provide some more info. Typically, when something like this happens it’s because the PSU PowerShell host doesn’t have a feature implemented (like support for Get-Credential)

try {

}
catch {
$_.Exception.StackTrace
}

@adam I added the StackTrace and the log shows this:

Mar 29, 2022 1:19 PM  Getting all mailboxes 
Mar 29, 2022 1:19 PM     at Microsoft.PowerShell.Commands.InvokeCommandCommand.GetHostDebugger()
   at Microsoft.PowerShell.Commands.InvokeCommandCommand.BeginProcessing()
   at System.Management.Automation.Cmdlet.DoBeginProcessing()
   at System.Management.Automation.CommandProcessorBase.DoBegin()

How do you have your environment setup? I mostly asked because if you have -HighPerformanceRunspace set, the debugger isn’t supported and it seems like Invoke-Command is trying to use it for some reason.

@adam, I am running PSU via a 2016 server using IIS hosting. I do not have the -HighPerformanceRunspace option set (unless it came enabled by default between upgrades I’ve performed). The AppPool is running under a domain account, which executes all scripts. I have two “custom” environments specified for PowerShell v5.1 and 7.x, this was to address an issue in a previous version where Windows Updates caused the environments to get wonky and scripts to start failing execution.

Environments:

New-PSUEnvironment -Name "7.1.3" -Version "7.1.3" -Path "C:\Program Files\PowerShell\7\pwsh.exe" -Variables @('*') 
New-PSUEnvironment -Name "5.1.17763.1971" -Version "5.1.17763.1971" -Path "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Variables @('*') 
New-PSUEnvironment -Name "Integrated" -Version "Integrated" -Path "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Variables @('*') 
New-PSUEnvironment -Name "Pwsh7" -Version "Pwsh7" -Path "C:\Program Files\PowerShell\7\pwsh.exe" -Variables @('*') 
New-PSUEnvironment -Name "Posh5" -Version "Posh5" -Path "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Variables @('*')

Ok. That’s pretty weird since it’s coming from the PS SDK. This only happens in the integrated environment? Or running in any environment in PSU?

@adam I don’t understand why this makes a difference, but running it in the “Posh5” environment, it started working. If I set it back to Integrated, it fails. That doesn’t make sense to me since the Environments.ps1 I shared you can see both Integrated and Posh5 are using the same path. For now, I’ll leave the environment as Posh5 since that does appear to work at the moment. Notice the Integrated failed, as did Pwsh7 environment, but for whatever reason Posh5 environment works: