为了账号安全,请及时绑定邮箱和手机立即绑定

通过 C# 打开 Windows Powershell

通过 C# 打开 Windows Powershell

C#
幕布斯7119047 2022-11-21 20:39:31
我试图通过 C# 代码打开 Powershell,最终目标是通过 C# 编写命令行(不使用 powershell skript)。我做了一些研究并提出了这个代码片段,但由于某种原因它只是没有打开 Powershell。Powershell 打开的代码需要改什么?//Opening Powershellprivate void Execute(){ProcessStartInfo startInfo = new ProcessStartInfo{FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",RedirectStandardOutput = true,RedirectStandardError = true,UseShellExecute = false,CreateNoWindow = true,};Process pro = Process.Start(startInfo);pro.WaitForExit();Thread.Sleep(3000);pro.Close();}
查看完整描述

1 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

我玩过这个。也许还有其他一些方法可以做到这一点,但这也有效。由于您需要一些初始设置,我认为您需要使用EnvironmentVariables,如果这样做,您还需要添加


startInfo.UseShellExecute = false;

所以一个可行的例子是


    static void Main(string[] args)

    {

        OpenPowerShell(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe");

    }


    static void OpenPowerShell(string path)

    {

        ProcessStartInfo startInfo = new ProcessStartInfo(path);

        startInfo.UseShellExecute = false;

        startInfo.EnvironmentVariables.Add("RedirectStandardOutput", "true");

        startInfo.EnvironmentVariables.Add("RedirectStandardError", "true");

        startInfo.EnvironmentVariables.Add("UseShellExecute", "false");

        startInfo.EnvironmentVariables.Add("CreateNoWindow", "true");

        Process.Start(startInfo);

    }

或者,如果您对另一个窗口没问题,只需:


    static void Main(string[] args)

    {

        OpenPowerShell(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe");

    }


    static void OpenPowerShell(string path)

    {

        Process.Start(path);

    }


查看完整回答
反对 回复 2022-11-21
  • 1 回答
  • 0 关注
  • 230 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号