尝试让 powershell 在 C#/Visual Studio 中工作

2024-01-10

我试图学习如何在 C# 中使用 powershell 我正在关注本教程 https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

但是,当我运行它时,我收到此错误:

未处理的异常。 System.InvalidProgramException:公共语言运行时检测到无效程序。 在 System.Management.Automation.PowerShell.Create() 在 C:\Users\ncox\source\repos\desktopAdmin365\Program.cs 中的desktopAdmin365.Program.Main(String[] args):第11行

C:\Users\ncox\source\repos\desktopAdmin365\bin\Debug\netcoreapp3.0\desktopAdmin365.exe(进程17464)退出,代码为-532462766。

我确信在包含解决方案资源管理器中的引用/依赖项时我错过了一些东西,但我没有运气通过谷歌找出哪一个

这是代码

using System;
using System.Management.Automation;
using System.Collections.ObjectModel;
namespace desktopAdmin365
{
    class Program
    {
        static void Main(string[] args)
        {
            using (PowerShell PowerShellInstance  = PowerShell.Create())
            { 
                PowerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; " +
                "$d; $s; $param1; get-service");
            }
        }
    }
}

如果您查看项目中的依赖项,您可能会看到一条关于使用 .NETFramework 恢复包且可能不兼容的警告。

您的项目是.NET core,因此您可能需要安装Powershell Core。

  • https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-windows?view=powershell-6 https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-windows?view=powershell-6

或者,切换到 .net 框架解决方案,它将起作用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试让 powershell 在 C#/Visual Studio 中工作 的相关文章

随机推荐