【问题标题】:Running PowerShell from .NET Core - Command Not found从 .NET Core 运行 PowerShell - 找不到命令
【发布时间】:2021-01-02 08:28:53
【问题描述】:

我正在使用 .NET Core 通过 Powershell 编写一些自动化程序, 我安装了以下 nugets:

Microsoft.PowerShell.Commands.Management
Microsoft.PowerShell.SDK
Microsoft.WSMan.Management
System.Management.Automation

并且正在使用以下代码:

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("$service = Get-CimInstance -ClassName Win32_Service -Filter \"name = 'MyNewService\'\"");

pipeline.Commands.AddScript("$service.DisplayName");

得到以下错误

System.Management.Automation.CommandNotFoundException:“‘Get-CimInstance’一词未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。
检查名称的拼写,如果包含路径,请验证路径是否正确,然后重试。'

任何想法如何解决这个问题,所以它会识别命令?

【问题讨论】:

  • 可能没有安装或加载带有该命令的模块。你能手动运行 cmdlt 吗?
  • CIM 是在 PowerShell 版本 3 中引入的。也许您还在使用版本 2?
  • @Theo 我使用的是版本 6。
  • 您的System.Management.Automation 版本是什么?
  • Import-Module CIMCmdlets?从命令行运行,我理所当然地认为标准的东西在 psmodulepath 中。也许这不是您在创建自己的运行空间时免费获得的东西。

标签: powershell asp.net-core


【解决方案1】:

问题实际上是与正在通过的版本的兼容性问题。您可以通过获取 Runspace 的 SessionStateProxy 的错误值来查看:

var err=run.SessionStateProxy.PSVariable.GetValue("error");

它会显示版本存在问题:

模块“C:\windows\system32\WindowsPowerShell\v1.0\Modules\CIMCmdlets\CIMCmdlets.psd1”不支持当前的 PowerShell 版本“Core”。它支持的版本是“桌面”。使用 'Import-Module -SkipEditionCheck' 忽略此模块的兼容性。

这提供了解决方案。 InitialSessionState 的 ImportPSModule 无法执行此操作,因此请尝试以下操作:

using System.Management.Automation;
using System.Management.Automation.Runspaces;
InitialSessionState _initialSessionState = InitialSessionState.CreateDefault2();
_initialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
var script="$service = Get-CimInstance -ClassName Win32_Service -Filter \"name = 'MyNewService\'\";$service.DisplayName";
using (var run = RunspaceFactory.CreateRunspace(_initialSessionState))
{
       run.Open();
       var ps = PowerShell.Create(run);
       ps.AddCommand("Import-Module");
       ps.AddParameter("SkipEditionCheck");
       ps.AddArgument("CIMcmdlets");
       ps.Invoke();
       var err = run.SessionStateProxy.PSVariable.GetValue("error");
       System.Diagnostics.Debug.WriteLine(err);//This will reveal any error loading
       ps.Commands.AddScript(script);
       var results = ps.Invoke();
       run.Close();
       return results;
}

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 2018-02-15
    • 2021-10-25
    • 2018-02-16
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    相关资源
    最近更新 更多