03-18-2024, 06:42 AM
https://www.nuget.org/packages/Microsoft.PowerShell.SDK
2 examples.
2 examples.
// script "nuget PowerShell.cs"
/*/ nuget ps\Microsoft.PowerShell.SDK; /*/
using System.Management.Automation;
PS();
void PS() {
var psCode = """
& 'C:\Program Files\Windows NT\Accessories\wordpad.exe'
""";
using var ps = PowerShell.Create();
ps.AddScript(psCode);
ps.Invoke();
}
// 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) {
print.it(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) {
print.it("ERROR: " + error.ToString());
}
return results;
}
}
}