c# - 发生异常:运行简单的 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 上运行
解决方案
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 安装。
推荐阅读
- python - Python 没有意识到安装了 sqlalchemy 扩展?
- python - 如何转换 torchscript 模型以在 OpenCV 中使用它?
- tk - 我收到 HTTP 错误 404 使此代码下载 YouTube 知道为什么我很确定链接尝试加载没有任何问题
- javascript - Safari 错误。当尝试使用模糊过滤器为 svg 转换设置动画时,safari 非常滞后
- r - 使用 rbind 函数 rbind 三个数据库
- angular - d3._3d() 不是函数
- java - 请解释一下 java 中 repaint() 方法的工作原理?
- c# - ASP.NET Core 3 - 覆盖自定义的默认 ControllerFactory,在其他情况下如何保存调用?
- amazon-web-services - 推送到 ECR 的 buildspec.yml 抛出此错误“命令未成功退出 $(aws ecr get-login --no-include-email --region us-east-1)”
- javascript - 使用 D365 中的 Javascript 使用模板创建电子邮件并以模态方式打开