通过 C# 打开 Windows Powershell

我试图通过 C# 代码打开 Powershell,最终目标是通过 C# 编写命令行(不使用 powershell skript)。


我做了一些研究并提出了这个代码片段,但由于某种原因它只是没有打开 Powershell。Powershell 打开的代码需要改什么?


//Opening Powershell

private 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();

}


幕布斯7119047
浏览 231回答 1
1回答

收到一只叮咚

我玩过这个。也许还有其他一些方法可以做到这一点,但这也有效。由于您需要一些初始设置,我认为您需要使用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);    }
打开App,查看更多内容
随时随地看视频慕课网APP