Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Executing PowerShell code at the API level
#2
https://www.nuget.org/packages/Microsoft.PowerShell.SDK

2 examples.

Code:
Copy      Help
// 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();
}

Code:
Copy      Help
// 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;
        }
    }
}


Messages In This Thread
RE: Executing PowerShell code at the API level - by Gintaras - 03-18-2024, 06:42 AM

Forum Jump:


Users browsing this thread: 18 Guest(s)