gpt4 book ai didi

c# - 在 C# 应用程序中运行 PowerShell 进程并与之交互

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:48 25 4
gpt4 key购买 nike

我正在创建一个需要与 PowerShell 交互的 C#/WPF 应用程序(基本上是运行命令和脚本)。创建进程并启动它不是问题,这很容易,但是当目标是在没有任何脚本的情况下启动它并让它稍后运行命令和脚本时,这就变得更加困难了:

  1. 启动 C# 应用
  2. 并行运行 PowerShell 进程
  3. [...] 做一些其他事情 [...]
  4. 在进程上运行命令

我尝试了多种解决方案。使用 System.Diagnostics.Process 类,我能够启动进程,让它运行,但即使我重定向流,写入标准输入也不起作用:

var startInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = "-ExecutionPolicy Bypass -NoLogo -NoExit",
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden
};
_ps = new Process()
{
EnableRaisingEvents = true,
StartInfo = startInfo
};
_ps.Start();

[...]

_ps.StandardInput.WriteLine(TextBox_Input.Text); // No effect

使用 System.Management.Automation.PowerShell 类并不是更好,我可以准备管道(添加要执行的脚本),调用它,但是,我不能稍后运行脚本保持活着的过程。

我需要尽快启动进程,以便能够向它发送命令并尽可能快地运行它们(并避免启动会导致延迟的进程)。

最佳答案

如评论中所述,在应用程序启动时设置(并打开)一个运行空间:

Runspace rs;
public MainWindow()
{
InitializeComponent();
rs = RunspaceFactory.CreateRunspace();
rs.Open();
}

现在,您只需要一个创建 PowerShell 实例并在运行空间中执行它的函数:

private Collection<PSObject> RunScript(string script)
{
using(PowerShell ps = PowerShell.Create())
{
ps.AddScript(script);
ps.Runspace = rs;
return ps.Invoke();
}
}

然后,在用于运行用户输入的脚本的事件处理程序中:

private void button_Click(object sender, RoutedEventArgs e)
{
Collection<PSObject> returnedObjects = RunScript(TextBox_Input.Text);
// do what you want with returnedObjects if necessary
}

当然,这是一个过于简化的示例。在现实世界的应用程序中,您将检查 error and warning streams , 使用 APM (BeginInvoke()/EndInvoke()) 等

关于c# - 在 C# 应用程序中运行 PowerShell 进程并与之交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35814747/

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