前言
最近,在使用PowerShell做一些事情,然后需要放到AKS运行。
正文
一开始,使用的System.Management.Automation调用PowerShell,后来,发现有些功能在AKS下面执行不了,后面才想到使用Process的方式,如下:
public void ExecutePowerShell(string script)
{
try
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "pwsh",
Arguments = $"-Command {script}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
System.Diagnostics.Process process = new System.Diagnostics.Process
{
StartInfo = startInfo
};
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
Console.WriteLine("Output:");
Console.WriteLine(output);
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine("Error:");
Console.WriteLine(error);
}
int exitCode = process.ExitCode;
Console.WriteLine($"Exit Code: {exitCode}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
Console.WriteLine(ex.StackTrace.ToString());
}
}
这里就是新建一个Process,使用pwsh调用PowerShell,只需要传入对应的脚本就行了。
如果命令非常多,可以试试StringBuilder来新建PowerShell脚本。