无法使PowerShell Scriptlet在C#中运行

时间:2016-08-09 09:15:03

标签: c# powershell

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

Stop-WebAppPool "Test1234"

这很有用。我检查了“Test1234”应用程序池已停止。

然而,当我把它作为test.ps1文件并从我的C#代码中调用它时,它没有用。

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();

它没有抛出任何错误但没有奏效。为什么会发生这种情况以及如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

如果需要从C#调用powershell,可以考虑使用System.Management.Automation nuget包。如msdn docs中所述,此nuget包将允许您按如下方式运行powershell:

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