Powershell 通过.NET内核与Get WmiObject交互
我需要获取有关系统的信息。我可以通过Powershell获取WmiObject。但我需要用.NET核心应用程序收集它 我能够执行一些基本命令,比如Get命令或Get进程 当我尝试exexute获取WmiObject时,出现了以下错误 术语“Get-WMIOObject”未被识别为cmdlet的名称, 函数、脚本文件或可操作程序。 检查单词的拼写 名称,或者如果包含路径,请验证该路径是否正确,并且 再试一次 使用(Get-CIMInstance CIM_ComputerSystem)执行此命令时出现相同问题。名称 术语“Get-CIMInstance”未被识别为cmdlet的名称, 函数、脚本文件或可操作程序。检查单词的拼写 名称,或者如果包含路径,请验证该路径是否正确,并且 再试一次 您知道使用powershell执行Get-CIMInstance或Get-WmiObjet with dotnet core的变通方法吗 更新Powershell 通过.NET内核与Get WmiObject交互,powershell,.net-core,get-wmiobject,powershell-6.0,Powershell,.net Core,Get Wmiobject,Powershell 6.0,我需要获取有关系统的信息。我可以通过Powershell获取WmiObject。但我需要用.NET核心应用程序收集它 我能够执行一些基本命令,比如Get命令或Get进程 当我尝试exexute获取WmiObject时,出现了以下错误 术语“Get-WMIOObject”未被识别为cmdlet的名称, 函数、脚本文件或可操作程序。 检查单词的拼写 名称,或者如果包含路径,请验证该路径是否正确,并且 再试一次 使用(Get-CIMInstance CIM_ComputerSystem)执行此命令时出
private PSDataCollection InvokeScript(字符串脚本)
{
使用(PowerShell ps=PowerShell.Create())
{
Runspace Runspace=RunspaceFactory.CreateRunspace();
Open();
ps.运行空间=运行空间;
ps.AddScript(脚本);
ps.Streams.Error.DataAdded+=Error\u DataAdded;
PSDataCollection outputCollection=新PSDataCollection();
outputCollection.DataAdded+=outputCollection\u DataAdded;
var result=ps.BeginInvoke(null,outputCollection);
foreach(ps.Streams.Error中的变量项)
{
_logger.LogError(item.ToString());
}
_logger.LogInformation(“执行已停止。执行状态:“+ps.InvocationStateInfo.state”);
返回输出集合;
}
}
调用脚本
Get命令时,我在结果中找到了Get WmiObject。但是当我调用获取WmiObject
时,它不会运行 您实际上不需要获取WmiObject
,您可以添加对Microsoft.Management.Infrastructure
命名空间的引用。。。请参阅使用msdn中的c#的示例:Get-Ciminstance应与windows中最新的powershell 6一起使用。在dotnet core中,我使用$PSVersionTable.PSVersion,这将返回6.2.2。但是Get命令–模块CIMCmdlet不返回增强。如何导入模块CIMCmdlet?虽然Get-CimInstance
在PowerShell 6中工作,但是CIMCmdlet
模块并未随PowerShell 6 SDK一起发布。计划在PowerShell 7 SDK中包含CIMCmdlet
模块。见本期:
private PSDataCollection<PSObject> InvokeScript(string script)
{
using (PowerShell ps = PowerShell.Create())
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
ps.Runspace = runspace;
ps.AddScript(script);
ps.Streams.Error.DataAdded += Error_DataAdded;
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += OutputCollection_DataAdded;
var result = ps.BeginInvoke<PSObject, PSObject>(null, outputCollection);
foreach (var item in ps.Streams.Error)
{
_logger.LogError(item.ToString());
}
_logger.LogInformation("Execution has stopped. Execution state: " + ps.InvocationStateInfo.State);
return outputCollection;
}
}