本文告诉大家如何在 dotnet core 通过 Host PowerShell 的方法使用 PowerShell 脚本

本文提供的方法需要在 dotnet core 2.1 和以上的版本,对于 dotnet core 2.1 以下暂时只能通过命令行调用 PowerShell.exe 的方法调用

在使用之前请创建一个 dotnet core 程序然后安装下面几个 Nuget 库

通过 System.Management.Automation.PowerShell 可以快速使用 PowerShell 脚本

使用 PowerShell.Create() 创建一个 PowerShell 类,在 PowerShell 类先添加脚本,然后就可以运行,运行函数会返回运行的返回的内容

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

如使用下面的脚本

([System.Management.Automation.ActionPreference], [System.Management.Automation.AliasAttribute]).FullName

可以直接调用上面封装的函数

            Execute("([System.Management.Automation.ActionPreference], [System.Management.Automation.AliasAttribute]).FullName");

在命令行使用 dotnet run 可以看到输出

System.Management.Automation.ActionPreferenceSystem.Management.Automation.AliasAttribute

本文使用的代码请看 github

官方例子

https://stackoverflow.com/a/47777636/6116637


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/dotnet-core-%E4%BD%BF%E7%94%A8-PowerShell-%E8%84%9A%E6%9C%AC.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号

欢迎进入 Eleven 老师组建的 .NET 社区

以上广告全是友情推广,无盈利