Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Execute the powershell code with another method
#2
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;
}
}
}


Messages In This Thread
RE: Execute the powershell code with another method - by Gintaras - 08-10-2022, 08:32 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)