无法使PowerShell Scriptlet在c#中工作

本文关键字:工作 Scriptlet PowerShell | 更新日期: 2023-09-27 18:01:40

我试图通过从PowerShell发出以下命令来停止应用程序池

Stop-WebAppPool "Test1234"

这工作。我检查了"Test1234"应用程序池已经停止。

然而,当我把它作为一个测试。

c#代码

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:'test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();

它没有抛出任何错误,但不工作。为什么会发生这种情况,如何让它工作?

无法使PowerShell Scriptlet在c#中工作

如果你需要从c#中调用powershell,你可以考虑使用System.Management.Automation内核包。正如msdn文档中所描述的,这个nuget包将允许您按照如下方式运行powershell:

using System.Management.Automation;
// ...
PowerShell ps = PowerShell.Create();
ps.AddCommand("Stop-WebAppPool");
ps.AddArgument("Test1234");
ps.Invoke();