Search code examples
c#powershellasp.net-corekestrel-http-server

ASP.Net core 2 - powershell remoting works only in IIS Express (Kestrel not working)


I'm trying to connect powershell session from my ASP.Net Core 2 app (.NET Framework 4.6.2 as a platform) to my Exchange server. Code works perfectly when using IIS Express (debug in Visual studio), but I had no luck using Kestrel.

Exchange is set up corretly. I can successfully connect using powershell or using following code with IIS Express.

Create powershell connection:

var psOptions = new PSSessionOption()
{
    SkipCACheck = true,
    SkipCNCheck = true,
    SkipRevocationCheck = true
};
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://" + _server + "/powershell?serializationLevel=Full"),
    "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credentials);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SetSessionOptions(psOptions);
_runspace = RunspaceFactory.CreateRunspace(connectionInfo);

_runspace.Open();

Error:

Hosting environment: Production
Content root path: path
Now listening on: http://127.0.0.1:12006
Application started. Press Ctrl+C to shut down.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLOGQUBGFLJ1", Request id "0HLOGQUBGFLJ1:00000001": An unhandled exception was thrown by the application.
System.Management.Automation.Remoting.PSRemotingTransportException: Connecting to remote server hostname failed with the following error message : The WinRM client sent a request to an HTTP server and got a response saying the requested HTTP URL was not available. This is usually returned by a HTTP server that does not support the WS-Management protocol. For more information, see the about_Remote_Troubleshooting Help topic.
   at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()

Solution

  • There was a problem on Exchange side. WinRM HTTPS listener was missing. You can check listeners with command winrm e winrm/config/listener.

    PS C:\WINDOWS\system32> winrm e winrm/config/listener
    Listener
        Address = *
        Transport = HTTP
        Port = 5985
        Hostname
        Enabled = true
        URLPrefix = wsman
        CertificateThumbprint
        ListeningOn = <hidden>
    
    
    
    Listener
        Address = *
        Transport = HTTPS
        Port = 5986
        Hostname = <hidden>
        Enabled = true
        URLPrefix = wsman
        CertificateThumbprint = <hidden>
        ListeningOn = <hidden>