![](/img/trans.png)
[英]Is there a way to capture powershell script executed output without using System.Management.Automation
[英]Capture standart output of powershell script executed from .NET application
讓我們假設我有一個非常簡單的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的方法
在“myscript.ps1”上放置Out-String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.