2

I search a embedded PowerShell console to my projects C# (Added from Toolbox). I found some simples examples to execute a command and have the return value (PowerShell. Create (), AddScript, AddCommand, Invoke, ...) It is simple but it does not allow the inoput user. Of more the context is not kept and a new console is created at each run (lost root path).

I also found an example PoshConsole, but it is a complete labyrinthine system and it is made in xaml - techno which I master not at all (and which apparently is not compatible with Form classic - maybe I make a mistake?)

Here we are, I hope to have been clear - Sorry I'm french Beforehand thank you.

1 Answers1

1

Executing Powershell from C# is known as hosting PS. When you host PS, and want to have some kind of UI that PS and the user both interact directly with, then you need to implement a "PSHost" (google "Powershell Host"). As a PSHost designer then you will need to decide what input/output technology to use. Common examples are: GUI and console style UIs.

Implementing a PSHost then gives scripts running in the hosted environment access to cmdlets like: write-host and read-host.

An alternative to implementing a PSHost is to do all UI input/output in your C# program and use PS as just a scripting/execution engine.

As far as preserving context, every time you instantiate a System.management.automation.powershell (via Create()) you will get a new PS environment. To not get a new environment don't create a new Powershell.

If your host program design is such that you must create a new Powershell but still want to preserve context then you will have to save/restore context programmatically. You can write scripts that you invoke from C# to do each task. The save script will be the last thing you do in a Powershell before you destroy it and the restore script will the first thing you do in a new Powershell.

Χpẘ
  • 3,403
  • 1
  • 13
  • 22