question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

PowerShell SDK 7.2.x unable to connect to Exchange remotes

See original GitHub issue

name: Bug report🐛 about: Unable to connect to exchange powershell with PowerShell.net 7.1x title: “Unable to connect to exchange powershell with PowerShell.net 7.1x” labels: Needs-Triage assignees: ‘’


Steps to reproduce

//Set Credential
SecureString s = new SecureString();
Config.GetValue<string>(pass).ToCharArray().ToList().ForEach(p => s.AppendChar(p));

//Use a public client app to get a OAuth token for CUBOT
var publicClientApplication = PublicClientApplicationBuilder.Create(appid).WithTenantId(Config.GetSection("AzureAd").GetValue<string>("tenantId")).Build();
var tokenworker = publicClientApplication.AcquireTokenByUsernamePassword(new string[] { "https://outlook.office365.com/.default" }, Config.GetValue<string>(user), s).ExecuteAsync();
tokenworker.Wait();

Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();


s = new SecureString();
//convert the OAuth Token into a SecureString
$"Bearer {tokenworker.Result.AccessToken}".ToCharArray().ToList().ForEach(p => s.AppendChar(p));

//Create a Powershell Credential using the CUBot User and the OAuth SecureString
PSCred = new PSCredential(Config.GetValue<string>("poshuser"), s);

command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
//convert basic auth to modern with the query string
command.AddParameter("ConnectionUri", new Uri("https://outlook.office365.com/powershell-liveid/?BasicAuthToOAuthConversion=true"));
command.AddParameter("Credential", PSCred);
//Yes still basic auth but we are passing the OAuth token not a password
command.AddParameter("Authentication", "Basic");
command.AddParameter("AllowRedirection");
powershell.Commands = command;

runspace.Open();
powershell.Runspace = runspace;
Result = powershell.Invoke(); 

Expected behavior

successfully connects to exchange online

Actual behavior

unable to connect

Environment data

Name                           Value
----                           -----
PSVersion                      7.1.3
PSEdition                      Core
GitCommitId                    7.1.3
OS                             Microsoft Windows 10.0.21387
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

C# .net core 5
Windows 10/Azure App Service

Issue is in all 7.1.x builds of the SDK System.Management.Automation namespaces. This script works in 7.0.x but does not in 7.1.x

The error you get is to unable to connect to remote resource/connection closed. Again this code works in 7.0.x (inc 7.0.6) but does not in 7.1.3

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:1
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
techienickbcommented, Sep 6, 2021

Any update on this issue? Testing in .net 6 and the latest preview (7.2.0) of the SDK.


`fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.Management.Automation.RuntimeException: An error has occurred which PowerShell cannot handle. A remote session might have ended.
       ---> System.Management.Automation.Remoting.PSRemotingDataStructureException: An error has occurred which PowerShell cannot handle. A remote session might have ended.
       ---> System.NotSupportedException: BinaryFormatter serialization and deserialization are disabled within this application. See https://aka.ms/binaryformatter for more information.
         at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph) in System.Runtime.Serialization.Formatters.dll:token 0x60001c7+0x11
         at System.Management.Automation.Remoting.RemoteSessionCapability.GetCurrentTimeZoneInByteFormat() in System.Management.Automation.dll:token 0x6004807+0x15
         at System.Management.Automation.RemotingEncoder.GenerateClientSessionCapability(RemoteSessionCapability capability, Guid runspacePoolId) in System.Management.Automation.dll:token 0x6003537+0x7
         at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl.HandleNegotiationSendingStateChange() in System.Management.Automation.dll:token 0x6004654+0x0
         at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl.HandleStateChanged(Object sender, RemoteSessionStateEventArgs arg) in System.Management.Automation.dll:token 0x6004653+0x2a
         at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerStateMachine.RaiseStateMachineEvents() in System.Management.Automation.dll:token 0x600460f+0x10
         at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerStateMachine.ProcessEvents() in System.Management.Automation.dll:token 0x600460d+0x56
         --- End of inner exception stack trace ---
         at Microsoft.Exchange.Management.ExoPowershellSnapin.NewExoPSSession.HandleError(PSDataCollection1 errors) in Microsoft.Exchange.Management.ExoPowershellGalleryModule.dll:token 0x600007b+0x37
         at Microsoft.Exchange.Management.ExoPowershellSnapin.NewExoPSSession.ExecutePsCommand(PSCommand command) in Microsoft.Exchange.Management.ExoPowershellGalleryModule.dll:token 0x6000076+0x1d
         at Microsoft.Exchange.Management.ExoPowershellSnapin.NewExoPSSession.ProcessNewConnection() in Microsoft.Exchange.Management.ExoPowershellGalleryModule.dll:token 0x6000077+0x57c
         at Microsoft.Exchange.Management.ExoPowershellSnapin.NewExoPSSession.ProcessRecord() in Microsoft.Exchange.Management.ExoPowershellGalleryModule.dll:token 0x600006e+0xf
         at System.Management.Automation.Cmdlet.DoProcessRecord() in System.Management.Automation.dll:token 0x6001e2a+0x0
         at System.Management.Automation.CommandProcessor.ProcessRecord() in System.Management.Automation.dll:token 0x6002100+0x0
         --- End of inner exception stack trace ---
         at System.Management.Automation.Runspaces.AsyncResult.EndInvoke() in System.Management.Automation.dll:token 0x60051a6+0x82
         at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult) in System.Management.Automation.dll:token 0x60027ff+0x67
         at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization) in System.Private.CoreLib.dll:token 0x60031be+0xf
      --- End of stack trace from previous location ---
         at CU.M365Management.PS.HostedRunspace.RunScript(String scriptContents, Dictionary2 scriptParameters) in H:\source\repos\CU M365 Management Web\CU.M365Management\PS\RunspaceStarter.cs:line 89
         at CU.M365Management.Controllers.NewExPoShController.Get() in H:\source\repos\CU M365 Management Web\CU.M365Management\Controllers\NewExPoShController.cs:line 34
         at lambda_method923(Closure , Object )
         at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x6000fc3+0x5b
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x60009c1+0x153
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x60009bd+0x6a
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x60009ba+0x15
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x60009b5+0x39a
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvokerrollerActionInvokrollerActrollerActionrollerActionInvorollerAcrollerArollerollerollerorollerActionInvoker invoker, Task lastTask, SrollerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x60009c2+0x6e
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x6000a81+0x65
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x6000a7e+0x172
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker) in Microsoft.AspNetCore.Mvc.Core.dll:token 0x6000a7e+0x21d
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) in Microsoft.AspNetCore.Routing.dll:token 0x60000ab+0x5e
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) in Microsoft.AspNetCore.Authorization.Policy.dll:token 0x6000013+0x16b
         at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) in Microsoft.AspNetCore.Authentication.dll:token 0x6000049+0x3be
         at NSwag.AspNetCore.Middlewares.SwaggerUiIndexMiddleware.Invoke(HttpContext context) in NSwag.AspNetCore.dll:token 0x6000099+0x27a
         at NSwag.AspNetCore.Middlewares.RedirectToIndexMiddleware.Invoke(HttpContext context) in NSwag.AspNetCore.dll:token 0x6000097+0x178
         at NSwag.AspNetCore.Middlewares.SwaggerUiIndexMiddleware.Invoke(HttpContext context) in NSwag.AspNetCore.dll:token 0x6000099+0x27a
         at NSwag.AspNetCore.Middlewares.RedirectToIndexMiddleware.Invoke(HttpContext context) in NSwag.AspNetCore.dll:token 0x6000097+0x178
         at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context) in NSwag.AspNetCore.dll:token 0x6000093+0x204
         at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context) in NSwag.AspNetCore.dll:token 0x6000093+0x204
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) in Microsoft.AspNetCore.Diagnostics.dll:token 0x60000aa+0x82
0reactions
solbirncommented, Dec 17, 2021

Any updates? Can’t PS remote from Azure Function (C#, net6) even when EnableUnsafeBinaryFormatterSerialization is enabled in project

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to connect to Exchange Online PowerShell Module
Unable to connect to Exchange Online PowerShell Module · Open PowerShell: Look for PowerShell in the start menu and open it. · Load...
Read more >
Unable to Connect to Exchange via Powershell remote
I'm trying to connec to an on premise Exchange 2016 server via remote powershell using the below 3 commands. Powershell. $LiveCred = Get- ......
Read more >
how to get winrm to use powershell 7 for remote sessions ...
When remoting, default to running PowerShell Core v7.x on the # the target machines: $PSSessionConfigurationName = 'PowerShell.7'.
Read more >
How to Install Azure AD module in PowerShell
Open PowerShell with Elevated permissions. – Right-click on your Start menu (or press Windows key + X) · Install Azure AD Module. Type...
Read more >
PowerShell – Kemp Support
To enable it using the Web User Interface (WUI), go to Certificates & Security > Remote Access and select Enable API Interface. You...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found