'Why does running the Get-CsOnlineUser command in C# return "An error has occurred which PowerShell cannot handle. A remote session might have ended."

I've installed this package: https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?view=powershellsdk-7.0.0

And am able to run commands like Get-CsTenant | Select-Object DisplayName

But when I try to run this command: Get-CsOnlineUser | Select-Object UserPrincipalName, DisplayName, Name

With this C# code

PowerShell powershell = PowerShell.Create();
            try
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace())
                {
                    runspace.Open();
                    powershell.Runspace = runspace;
                    powershell.AddScript(@".\Connect.ps1");
                    powershell.Invoke();

                    var testOne = powershell.AddScript("Get-CsTenant | Select-Object DisplayName").Invoke().ToList();
                    var testTwo = powershell.AddScript("Get-CsOnlineUser | Select-Object  UserPrincipalName, DisplayName, Name").Invoke().ToList();
                }
                return testTwo;
            }
            catch (Exception ex)
            {
                var errors = powershell.Streams.Error.ToList();
                return null;
            }

I get this error message An error has occurred which PowerShell cannot handle. A remote session might have ended.

More error details

When running these commands in the powershell interface with the same credentials they work fine.



Solution 1:[1]

For me, I had to add the following to the PropertyGroup element in the Project File:

<EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>

I believe this is required for remote PowerShell usage after .NET 5.0.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian Reading