C# 发生异常:CLR/System.Management.Automation.Runspaces.PSSnapInException在运行简单PowerShell命令时发生异常

C# 发生异常:CLR/System.Management.Automation.Runspaces.PSSnapInException在运行简单PowerShell命令时发生异常,c#,powershell,C#,Powershell,我试图运行一个示例C#程序,该程序应该调用一个简单的PowerShell命令。 不幸的是,我收到以下错误消息: Exception has occurred: CLR/System.Management.Automation.Runspaces.PSSnapInException An unhandled exception of type 'System.Management.Automation.Runspaces.PSSnapInException' occurred in System.

我试图运行一个示例C#程序,该程序应该调用一个简单的PowerShell命令。 不幸的是,我收到以下错误消息:

Exception has occurred: CLR/System.Management.Automation.Runspaces.PSSnapInException
An unhandled exception of type 'System.Management.Automation.Runspaces.PSSnapInException' occurred in System.Management.Automation.dll: 'System error.'
   at System.Management.Automation.Runspaces.PSSnapInHelpers.LoadPSSnapInAssembly(PSSnapInInfo psSnapInInfo)
   at System.Management.Automation.Runspaces.InitialSessionState.ImportPSSnapIn(PSSnapInInfo psSnapInInfo, PSSnapInException& warning)
   at System.Management.Automation.Runspaces.InitialSessionState.CreateDefault()
   at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(PSHost host)
   at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()
   at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
   at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
   at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
   at System.Management.Automation.PowerShell.Invoke(IEnumerable input, PSInvocationSettings settings)
   at System.Management.Automation.PowerShell.Invoke()
   at ttps3.Program.Main(String[] args) in Z:\projects\easybell\ttps3\Program.cs:line 21

我在C#SDK 5和System.Management.Automation 7.1.3上运行。System.Management.Automation仅在中可用。您可以安装
Microsoft.PowerShell.SDK
nuget软件包

Microsoft.PowerShell.SDK

Microsoft.PowerShell.SDK是一个元包,它将PowerShell SDK的所有组件汇集到一个单独的NuGet包中。独立的.NET应用程序可以使用Microsoft.PowerShell.SDK运行任意PowerShell功能,而无需依赖任何外部PowerShell安装或库

系统、管理、自动化

System.Management.Automation
包是PowerShell SDK的核心,主要作为Microsoft.PowerShell.SDK的一项资产存在于NuGet上。但是,它也可以直接用作较小托管场景和版本目标模块的包

具体而言,
System.Management.Automation
包可能是PowerShell功能的首选提供者,在以下情况下:

  • 您只希望使用PowerShell语言功能(在
    System.Management.Automation.language
    命名空间中),如PowerShell解析器、AST和AST访问者API(例如用于PowerShell的静态分析)
  • 您只希望执行Microsoft.PowerShell.Core模块中的特定命令,并且可以在使用
    CreateDefault2
    工厂方法创建的会话状态下执行这些命令
PowerShellStandard.Library和其他PowerShell参考程序集


这些引用程序集不包括运行时,需要与引用程序集版本匹配的全局powershell安装。

代码是什么样子的?