Running PowerShell from .NET Core

前端 未结 4 554
感动是毒
感动是毒 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:52

    Looks like it is well supported as of .NET Core 2.0 and PowerShell 6 Beta 3 (although it was supported in Beta 1 and 2 also but not as easily), here is a link to the Host PowerShell documentation in the GitHub repo

    And they give a good sample application showing it running with .NET Core 2.0 and PowerShell Core v6.0.0-beta.3 and Later:

    https://github.com/PowerShell/PowerShell/tree/master/docs/host-powershell

    In order to get the correct packages into my NuGet package list I did need to add powershell-core as a new NuGet repository location which was:

    https://powershell.myget.org/F/powershell-core/api/v3/index.json

    I could then install the NuGet packages:

    install-package microsoft.powershell.sdk -version 6.0.0-rc
    install-package microsoft.powershell.commands.diagnostics -version 6.0.0-rc
    install-package microsoft.wsman.management -version 6.0.0-rc
    

    All three of these dependencies were required and then I could execute the following simple PowerShell command in my asp.net core MVC Web Application:

    public class PowerShellHelper
    {
        public void Execute(string command)
        {
            using (var ps = PowerShell.Create())
            {
                var results = ps.AddScript(command).Invoke();
                foreach (var result in results)
                {
                    Debug.Write(result.ToString());
                }
            }
        }
    }
    

提交回复
热议问题