繁体   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