我有一个Powershell脚本,我需要使用C#执行它
string psData = System.IO.File.ReadAllText(@"C:\Users\m\Desktop\power.ps1");
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(psData);
IAsyncResult result = PowerShellInstance.BeginInvoke();
while (!result.IsCompleted)
{
Logger.Info("Wait initiated");
Thread.Sleep(5000);
}
Logger.Info("Execution completed");
}
使用上述代码脚本正在执行,但如何将参数传递给Shell脚本
我更改了代码
string psData = System.IO.File.ReadAllText(@"C:\Users\m\Desktop\power.ps1");
Process pr = new Process();
var processStartInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \""+psData+"\" \"arg1\" \"arg2\"",
UseShellExecute = false
};
pr.StartInfo = processStartInfo;
pr.Start();
pr.WaitForExit();
最佳答案
使用AddArgument方法。
更多信息-> https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.powershell.addargument?view=pscore-6.2.0
--------旧答案-----------------
不能确定如何通过PowerShellInstance类来执行此操作,但是可以使用Process类来调用带有参数的PowerShell脚本。
var file = @"C:\<Directory>\GetServices.ps1";
var processStartInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy unrestricted \"{ps1File}\"",
UseShellExecute = false
};
Process.Start(startInfo);
有关更多信息-> https://duanenewman.net/blog/post/running-powershell-scripts-from-csharp/
编辑2
string psData = @"C:\Users\manis\Desktop\test.ps1";
Process pr = new Process();
var processStartInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file {psData} hello",
UseShellExecute = false
};
pr.StartInfo = processStartInfo;
pr.Start();
pr.WaitForExit();
我的Powershell脚本如下所示
param ($param1)
write-host $param1
关于c# - 如何在C#中将参数添加到powershellinstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61496938/