我们假设我有一个非常简单的powershell脚本myscript.ps1
,它写入标准输出:
get-location
现在我想从.net应用程序执行此脚本。我最后得到了下一个代码:
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();
它有效,但我认为使用System.Management.Automation
程序集来实现它应该更优雅:
using (PowerShell shell = PowerShell.Create())
{
shell.Commands.AddScript("myscript.ps1");
var r = shell.Invoke();
Console.WriteLine(r);
}
但Invoke
返回`PSObject的集合,我找不到访问stdout的方法
答案 0 :(得分:-1)
On“myscript.ps1”放在最后的Out-String