正在从.NET Core运行PowerShell-未找到命令

正在从.NET Core运行PowerShell-未找到命令,powershell,asp.net-core,Powershell,Asp.net Core,我正在使用.NET Core编写一些有关Powershell的自动化程序, 我安装了以下NUGET: Microsoft.PowerShell.Commands.Management Microsoft.PowerShell.SDK Microsoft.WSMan.Management System.Management.Automation 并使用以下代码: Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open

我正在使用.NET Core编写一些有关Powershell的自动化程序, 我安装了以下NUGET:

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、函数、脚本文件或可操作程序的名称。
请检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。”


有没有办法解决这个问题,这样它就可以识别这个命令?

这个问题实际上是与正在传递的版本的兼容性问题。您可以通过获取运行空间的SessionStateProxy的错误值来查看:

var err=run.SessionStateProxy.PSVariable.GetValue("error");
这将揭示版本中存在一个问题:

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

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

using System.Management.Automation;
using System.Management.Automation.Runspaces;

可能未安装或加载带有该命令的模块。您是否能够手动运行cmdlt?PowerShell版本3中引入了CIM。也许您仍在版本2上?@Theo我正在使用版本6。您的
系统.管理.自动化
版本是什么?
导入模块CIMCmdlet
?从命令行运行,我想当然地认为标准的东西在psmodulepath中。在创建自己的运行空间时,这可能不是免费的。
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;
}