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.