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

I have a lot of Powershell script code in my collection and I want to call them in QM3,

In QM3 the cookbook, I found an example of executing a Powershell script, But it's not very convenient,

I found the C# code below that powershell scripts can also be executed successfully in Linqpad too

so, I want to define the code as a class in QM3, so that it is convenient to call the Powershell Multi-line commands or function
For example,  like this
----------------------------------------------
string code = """
dir c:\ |
? name -EQ windows
""";
var stdout;
var stderr;
PSrun(code, stdout, stderr);

string[] args = {1,2};
PSfun("sum", args, stdout, stderr);
----------------------------------------------

I'm just getting started with C # and can't implement these features
Thanks for any advice and help
david



The Dll needs to be referenced: 
C:\windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
C# code: 
Code:
Copy      Help
 
class Program
{
static void Main(string[] args)
{

string Ps_code = "Get-Process | out-string";
Execute(Ps_code);
}

public static void Execute(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());
}
}
}
}


Call the Powershell function example:

Sum.ps1 
---------------------
function Sum
{
param([int]$first, [int]$second)
$result = $first + $second
return $result
}
Code:
Copy      Help
 
private static string script = File.ReadAllText(@"Path\Sum.ps1");
private static void CallPS1()
{
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();

PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddScript(script);
ps.Invoke();

ps.AddCommand("Sum").AddParameters(

new Dictionary<string, int>()
{
{"first", 5},
{"second", 4}
}
);

foreach (PSObject result in ps.Invoke())
{
Console.WriteLine("CallPS1()");
Console.WriteLine(result);
}
}
}


Messages In This Thread
Execute the powershell code with another method - by Davider - 08-09-2022, 11:42 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)