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

标签 c# .net powershell

假设我有一个非常简单的 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 的集合,我找不到访问标准输出的方法

最佳答案

在“myscript.ps1”上放在末尾的 Out-String

关于c# - 捕获从 .NET 应用程序执行的 powershell 脚本的标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30120301/

相关文章:

c# - .NET gmail API 身份验证(无需用户交互)

c# - 使用 System.IO 在 C# 中复制文件夹

powershell - 循环JSON对象,返回具体对象

html - DotAll 和多行正则表达式

c# - Windows Phone 7 Mango 的 FTP 客户端?

c# - 如何在图片框中放大一个点

.net - System.Net : Is there any other class inherited from ICredentials apart from NetworkCredential?

c# - 将 DbConnectionFactory 从 .net 迁移到 .net core

powershell - 如何使用 PowerShell 从 SharePoint 下载文件?

c# - 将函数从 c# 2008 转换为 Vb6.0 错误