Search code examples
c#powershellrunspace

Does a Powershell script using system.managment.automation would still run after its C# host die?


I want to add PowerShell capabilities to a C# program and I have embedded the system.managment.automation.dll assembly as a reference. I have found on StackOverflow two ways to call a PowerShell scrit from C# :

  • Using runspaces:

  • Not using runspaces:

    PowerShell powerShell = PowerShell.Create();
    powerShell.AddScript("my script");
    powerShell.Invoke();
    

According to this website, it seems the Powershell instance is tied to its C# host.

The Powershell runtime is invoked as a runspace and will, by default, process commands synchronously and deliver the results of processing to the host application so that they can be returned to the user.

Furthermore, the PowerShell script uses the embedded system.managment.automation.dll assembly and not the system-wide one, so the script would logically stop with its C# host.

Does the Powershell script would still run after the user close my program ? What about the two methods ?

PS: I want to support PowerShell v2.


Solution

  • Let's take this in reverse chronology:

    What about the two methods ?

    There's no such thing as running powershell code by "not using runspaces".

    The simple explanation is that a runspace is a core prerequisite - as the name implies, a runspace is the space in which powershell code runs.

    When you do:

    PowerShell powerShell = PowerShell.Create()
    

    a runspace is implicitly created and attached to the PowerShell instance.

    The only difference is that you simply defer control over the Runspace creation to the System.Management.Automation API, rather than instantiating it yourself.

    Does the Powershell script would still run after the user close my program ?

    The only circumstance under which the script would continue execution after the host application has terminated, would be when you connect to a remote runspace, ie. a runspace hosted in another process or on another computer.

    Otherwise, the runspace (implicit or not) will be disposed along with the rest of the host application when it exits.