08-10-2022, 08:32 AM
Need NuGet package Microsoft.PowerShell.SDK. It contains 300+ files (full copy of PowerShell 7). I tested it, works, but the NuGet tool does not install several files. In the future I should fix it. Now I could give instructions how to install these manually, if you need. Then code could be like this:
C# code:
// script "PowerShell2.cs" /*/ nuget ps\Microsoft.PowerShell.SDK; /*/
using System.Management.Automation;
print.clear();
string code = "Get-Process | out-string";
var results = PS.Invoke(code);
foreach (var result in results) {
Console.WriteLine(result.ToString());
}
static class PS {
public static System.Collections.ObjectModel.Collection<PSObject> Invoke(string command) {
using (var ps = PowerShell.Create()) {
ps.AddScript(command);
var results = ps.Invoke();
// report non-runspace-terminating errors, if any.
foreach (var error in ps.Streams.Error) {
Console.Error.WriteLine("ERROR: " + error.ToString());
}
return results;
}
}
}