使用Net在Linux环境下调用PowerShell

  前言

  最近,在使用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脚本。

posted @   霖雨  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
历史上的今天:
2018-11-26 SharePoint Online 自定义Modern UI表单
点击右上角即可分享
微信分享提示