簡體   English   中英

捕獲從.NET應用程序執行的powershell腳本的標准輸出

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM