1

I would like to emulate a powershell/powershell-ISE console with a winform. Using Powershell.Create()/Invoke(), I can do pretty much everything to replicate the behaviour, but I'm missing something regarding the change of runspace when entering a remote session. Consider the code below:

            PowerShell ps = PowerShell.Create();          
            ps.AddScript("$i = 1").Invoke();
            ps.AddScript("Enter-PSSession -computer localhost").Invoke();
            var obj = ps.AddScript("$i").Invoke();
            // obj contains 1, whereas I would expect not to find $i

I'm wondering how I could make it transparent for the user that typing enter-pssession would actually change the runspace, just like powershell.exe would do.

1 Answers1

2

Enter-PSSession isn't supported in the context of the PowerShell SDK.

In fact, it isn't even supported in regular scripting or via the CLI; it only works when invoked from an interactive PowerShell session - see GitHub issue #16350.

You'll see the problem:

  • if you run your program from an elevated session ("loopback" remoting to the same machine requires that)

  • if you examine the errors that occurred, via ps.Streams.Error:

    • When you use .AddScript(), any errors that occur during execution of the PowerShell code do not surface as exceptions in your C# program; instead, you must examine the .Streams.Error collection (.HadErrors is a Boolean that indicates whether any errors occurred) - see this answer for details.

You'll see the following error, which may be related to the PowerShell host that the SDK uses, Default Host, missing features required by Enter-PSSession:

Enter-PSSession : The method or operation is not implemented.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • thank you very much for your answer. Is there any way I can achieve what I'm trying to achieve ? any other way ? – Utilitaire CCV May 15 '22 at 20:40
  • 1
    I'm glad to hear it helped, @UtilitaireCCV; my pleasure. If you want to allow users to type arbitrary commands, including `Enter-PSSession`, you'd have to intercept `Enter-PSSession` calls and handle entering a remote runspace yourself, which sounds challenging. – mklement0 May 15 '22 at 20:43