Let's assume that I have very simple powershell script myscript.ps1
, which writes to standart output:
get-location
Now I want to execute this script from .net application. I ended up with next code:
var process = new Process
{
StartInfo = {
FileName = "powershell.exe",
Arguments = "-file \"myscript.ps1\"",
WorkingDirectory = Path.Combine(Environment.CurrentDirectory, "run"),
UseShellExecute = false,
RedirectStandardOutput = true
}
};
process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
And it works, but I think it should be more elegant way to do it using System.Management.Automation
assembly:
using (PowerShell shell = PowerShell.Create())
{
shell.Commands.AddScript("myscript.ps1");
var r = shell.Invoke();
Console.WriteLine(r);
}
But Invoke
returns collection of `PSObject, and I can't find way to get access to stdout
在“myscript.ps1”上放置Out-String
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.