Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

c# - Running PowerShell from .NET Core

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

I'm trying to run a PowerShell script in a new .net core 'websiteapi'. From what I can tell in order to run PowerShell on .net we need to add the

System.Management.Automation namespace.

This isn't possible for .net core ( or I haven't found the appropriate way to add it). There are a couple of NuGet packages which are also aimed at adding this DLL to project but those aren't compatible with .net core either. Is there a way to do this on .net core ? Here are some links I've tried but none of them are .net core specific:

http://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/

Referencing system.management.automation.dll in Visual Studio

https://www.nuget.org/packages/System.Management.Automation/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...