【问题标题】:PowerShell script run from C# is lacking several modules从 C# 运行的 PowerShell 脚本缺少几个模块
【发布时间】:2017-01-18 04:02:17
【问题描述】:
var runspace = RunspaceFactory.CreateRunspace()
runspace.Open();
var ps = PowerShell.Create()
ps.Runspace = runspace;
ps.AddCommand(...);
ps.Invoke()

在 C# 启动的运行时中缺少一些常规 shell 中存在的 cmdlet,例如Microsoft.PowerShell.LocalAccounts 模块中的所有命令:

Error: System.Management.Automation.CommandNotFoundException: The term 'New-LocalUser' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
  at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
  at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
  at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

通过比较常规 shell 和 C# 启动的 Get-Module -ListAvailable 输出,我注意到缺少多个模块:

  • AppBackgroundTask
  • 分配的访问权限
  • BitLocker
  • 配置CI
  • 后卫
  • Microsoft.PowerShell.LocalAccounts
  • MMAgent
  • 网络交换机管理器
  • PcsvDevice
  • PSWorkflow、PSWorkflowUtility
  • SmbShare、SmbWitness
  • 开始布局
  • Windows 搜索

版本 ($PSVersionTable) 在两个 shell 中报告为相同:5.1.14393.693

编辑

似乎是同一个问题和解决方案:Why do powershell modules not import when running powershell via start process in c#?

【问题讨论】:

  • 您可以将Import-Module 与该模块的完整路径一起使用,或者必须设置/修复PSModulePath,这是我的猜测。无论出于何种原因,在这种情况下都会有所不同。

标签: c# powershell


【解决方案1】:

您可以直接在脚本中导入模块,而不是尝试从 C# 中导入。

导入模块 bitlocker

例如。

【讨论】:

  • 没有帮助。实际上,根据 MSDN:Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command.
  • 您是否检查了正在启动的 PowerShell 版本?
猜你喜欢
  • 1970-01-01
  • 2019-09-30
  • 2021-09-11
  • 1970-01-01
  • 2015-12-16
  • 2018-12-29
  • 2020-11-06
  • 1970-01-01
  • 2021-08-16
相关资源
最近更新 更多