简体   繁体   English

捕获从.NET应用程序执行的powershell脚本的标准输出

[英]Capture standart output of powershell script executed from .NET application

Let's assume that I have very simple powershell script myscript.ps1 , which writes to standart output: 让我们假设我有一个非常简单的powershell脚本myscript.ps1 ,它写入标准输出:

get-location

Now I want to execute this script from .net application. 现在我想从.net应用程序执行此脚本。 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: 它有效,但我认为使用System.Management.Automation程序集应该是更优雅的方式:

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 但是Invoke返回了`PSObject的集合,我找不到访问stdout的方法

在“myscript.ps1”上放置Out-String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM