2

I am trying to run a simple PowerShell script in a sample .NetCore console application. I'm using the Microsoft.Powershell.SDK (7.2.4) package.

I am getting the following exception:

Cannot perform operation because the runspace is not in the 'Opened' state. Current state of runspace is 'Broken'.

Here is my sample application:

try
{
    var psInstance = PowerShell.Create();
    psInstance.AddScript("Get-Host");
    var returnObj = psInstance.Invoke();
    
    foreach ( var obj in returnObj.First().Members )
    {
        Console.WriteLine($"{obj.Name}: {obj.Value}");
    }

    psInstance.Runspace?.Close();
}
catch ( Exception e )
{
    Console.WriteLine(e);
    throw;
}

What am I doing wrong here? I saw some references to creating a "Custom Runspace,' but that seemed a little complicated for running a simple script.

JohnB
  • 3,921
  • 8
  • 49
  • 99
  • https://stackoverflow.com/questions/64671333/error-running-ps-in-netcore-app-cannot-perform-operation-because-the-runspace – Andrii Khomiak Jun 10 '22 at 20:45
  • @Andrii - I was able to get this working by following instructions for PowerShell streams and custom runspace pool. I'm a little confused as to why I would need to do so. Why does this not work with the default runspace? Default run space fails even with simple command like "Get-Date". Can you please explain in more detail? – JohnB Jun 10 '22 at 22:45
  • @Andrii - OK. Figured it out. I create a RunSpace, open it and then assign it to my PowerShell instance. – JohnB Jun 10 '22 at 23:11
  • At least with the current PowerShell Core SDK version, 7.2.4, your code works as-is, and I would expect it to work in earlier versions too: a default runspace is created and opened for you if you don't assign one explicitly to the PowerShell instance. You will see exceptions, however (which you catch), because some of the properties of the host object that `Get-Host` retrieves require a runspace to evaluate, so they can't be evaluated in C# code. – mklement0 Jun 10 '22 at 23:32

0 Answers0