C# 执行powerShell

 public async Task<string> RunPowerShellAsync(params string[] cmds)
        {
            // 创建一个新的进程以执行PowerShell命令
            using var process = new Process();
            process.StartInfo.FileName = "powershell.exe";
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();

            // 将命令发送到PowerShell进程并执行
            using var streamWriter = process.StandardInput;
            using var streamReader = process.StandardOutput;
            foreach (var cmd in cmds)
            {
                await streamWriter.WriteLineAsync(cmd);
            }
            await streamWriter.WriteLineAsync("exit");
            // 读取PowerShell输出并将其打印到控制台
            string output = await streamReader.ReadToEndAsync();
            process.WaitForExit();
            return output;
        }

 

posted on 2024-01-08 10:54  TanZhiWei  阅读(550)  评论(0编辑  收藏  举报