首页 > 解决方案 > 发生异常:运行简单的 PowerShell 命令时出现 CLR/System.Management.Automation.Runspaces.PSSnapInException

问题描述

我正在尝试运行一个示例 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 上运行

标签: c#powershell

解决方案


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 安装。


推荐阅读