gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:46:12 26 4
gpt4 key购买 nike

假设我有一个非常简单的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com