Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Execute the powershell code with another method
#3
Thanks for your help

Many times, I don't need to install Powershell7, it is enough to use Powershell5

I thought of another way, generate an exe program using the QM2 code below, Then call this program from QM3, No additional DLL files are required

Execution speed seems to be a little faster than using PsCmd2 command

Called in PS3 like this
--------------------------------------------------------
var commands = """
dir
Get-Process
""";
run.console("PSrun.exe", "{commands}");
--------------------------------------------------------

But two unresolved issues were encountered  Huh

Function PSrun
Code:
Copy      Help
;Todo1: Parse the received parameters

str pscode=
;Get-Process | out-string

CsScript x
x.SetOptions("references=System.Management.Automation.dll;System.Core.dll")
x.AddCode("")

str psout=x.Call("PS_Code.RunPs" pscode)

;Todo2: When an error occurs, an error message is output
;;;;;;;;and currently, when there is an error, it is returned as empty
out psout

#ret
using System;
using System.Management.Automation;

public class PS_Code
{
,public static void RunPs(string command)
,{
,,using (var ps = PowerShell.Create())
,,{
,,,var results = ps.AddScript(command).Invoke();
,,,foreach (var result in results)
,,,{
,,,,Console.WriteLine(result.ToString());
,,,}
,,,// report non-runspace-terminating errors, if any.
,,,foreach (var error in ps.Streams.Error)
,,,{
,,,,Console.Error.WriteLine("ERROR: " + error.ToString());
,,,}
,,}
,}
}


Messages In This Thread
RE: Execute the powershell code with another method - by Davider - 08-10-2022, 12:21 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)