Search code examples
c#-4.0powershell-3.0powershell-remoting

Powershell v3 Remoting from C# using Enter-PSsession


I am trying to use Enter-PSsession from C# to enable and use Powershell remoting to run commands remotely. Here is a code

Runspace remoteRunspace = Runspaces.RunspaceFactory.CreateRunspace();
remoteRunspace.Open();
powershell.Runspace = remoteRunspace;
PSCommand command = new PSCommand();
command.AddCommand("Enter-PSSession");
command.AddParameter("ComputerName", "remotehostname");
command.AddParameter("Credential", vmmCredential);
powershell.Commands = command;
powershell.Invoke();

I get CmdletInvocationException. Here is the details for the same.

System.Management.Automation.CmdletInvocationException was unhandled Message=The method or operation is not implemented. Source=System.Management.Automation WasThrownFromThrowStatement=false StackTrace: at > System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input, Hashtable errorResults, Boolean enumerate) at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecute(Array input, Hashtable errorResults) at System.Management.Automation.Internal.PipelineProcessor.Execute(Array input) at System.Management.Automation.Internal.PipelineProcessor.Execute() at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper() at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc() InnerException: System.Management.Automation.PSNotImplementedException Message=The method or operation is not implemented. Source=System.Management.Automation StackTrace: at > System.Management.Automation.Internal.Host.InternalHost.GetIHostSupportsInteractiveSession() at > System.Management.Automation.Internal.Host.InternalHost.PushRunspace(Runspace runspace) at Microsoft.PowerShell.Commands.EnterPSSessionCommand.ProcessRecord() at System.Management.Automation.Cmdlet.DoProcessRecord() at System.Management.Automation.CommandProcessor.ProcessRecord() InnerException:

If I try the Enter-PSsession directly from powershell I am able to start a remote session with no issues... Can anyone advice as to what is wrong in C# code


Solution

  • OK I was not able to get Enter-PSSession cmdlet from C# code but below is the code which I was able to use to do PS remoting using C#...

    int iRemotePort = 5985;
    string strShellURI = @"http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
    string strAppName = @"/wsman";
    AuthenticationMechanism auth = AuthenticationMechanism.Negotiate;
    
    WSManConnectionInfo ci = new WSManConnectionInfo(
        false,
        sRemote,
        iRemotePort,
        strAppName,
        strShellURI,
        creds);
    ci.AuthenticationMechanism = auth;
    
    Runspace runspace = RunspaceFactory.CreateRunspace(ci);
    runspace.Open();
    
    PowerShell psh = PowerShell.Create();
    psh.Runspace = runspace;
    

    You can now use psh to run the commands remotely.