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   TanZhiWei  阅读(602)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示