Running PowerShell from .NET Core

前端 未结 4 571
感动是毒
感动是毒 2020-12-09 08:18

Is there a way to run PowerShell scripts from .net-core ?

I\'m trying to run a PowerShell script in a new .net core \'website\\api\'. From what I can tell in order

4条回答
  •  无人及你
    2020-12-09 08:49

    Thx for @Roman and @JamesEby.

    If we can not use dotnet core 2.0 or later and we can use Process to run the PowerShell.exe in Windows.

    The path is C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe and we can use Process in this code.

            var process = new Process
            {
                StartInfo = new ProcessStartInfo(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
                    script)
                {
                    WorkingDirectory = Environment.CurrentDirectory,
                    RedirectStandardOutput = true,
                    CreateNoWindow = true,
                }
            };
            process.Start();
    
            var reader = process.StandardOutput;
            return reader.ReadToEnd();
    

    The script value is the PowerShell Script and the reader.ReadToEnd() return the power shell output text.

    See: https://stackoverflow.com/a/30846513/6116637

提交回复
热议问题