Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Executing PowerShell code at the API level
#11
After executing the following code, the following error will be prompted, but it can be successfully executed in the pwsh.exe command line
ERROR: Could not find a part of the path 'C:\Users\Administrator\Documents\LibreAutomate\Main\.compiled\ref'.
ERROR: Unable to find type [LockWorkStationClass].

 
Code:
Copy      Help
/*/ nuget ps\Microsoft.PowerShell.SDK; /*/
using System.Management.Automation;

print.clear();

string code = """
Add-Type @"
using System.Runtime.InteropServices;
public class LockWorkStationClass {
    [DllImport("user32.dll", SetLastError=true)]
    public static extern void LockWorkStation();
}
"@
[LockWorkStationClass]::LockWorkStation()
"""
;

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 Davider - 05-26-2024, 10:42 PM

Forum Jump:


Users browsing this thread: 4 Guest(s)