.net 如何从托管C++; 我试图使用托管C++函数中的PuthS壳类来执行WMI函数。

.net 如何从托管C++; 我试图使用托管C++函数中的PuthS壳类来执行WMI函数。,.net,c++,powershell,wmi,.net,C++,Powershell,Wmi,但是我不知道如何对从PowerShell.Invoke()方法返回的PSObject列表中的对象调用方法 (在命令行上,我只需执行(gwmi…).RequestStateChange(2)-但我看不到如何使用PowerShell类的几个方法添加() System::Management::Automation::PowerShell ^ ps = System::Management::Automation::PowerShell::Create(); ps->AddCommand("G

但是我不知道如何对从PowerShell.Invoke()方法返回的PSObject列表中的对象调用方法

(在命令行上,我只需执行(gwmi…).RequestStateChange(2)-但我看不到如何使用PowerShell类的几个方法添加()

System::Management::Automation::PowerShell ^ ps = System::Management::Automation::PowerShell::Create();

ps->AddCommand("Get-WMIObject");
ps->AddParameter("namespace", "root/virtualization");

p->AddParameter("class", "Msvm_ComputerSystem");

// we could add a filter to only return the VM in question but
// I had problems with quoting so choose the
// simplier route.
System::Collections::ObjectModel::Collection<System::Management::Automation::PSObject^>^ result = ps->Invoke();

System::String ^s = gcnew System::String( id.c_str() );

for (int i = 0; i < result->Count; i++ ) {

    if ( System::String::Compare( dynamic_cast<System::String ^>(result[i]->Members["Name"]->Value), s) == 0 ) {

        // Now what ? I want to call the RequestStateChange method on this VM
        return;
    }
}
System::Management::Automation::PowerShell ^ps=System::Management::Automation::PowerShell::Create();
ps->AddCommand(“获取WMIOObject”);
ps->AddParameter(“名称空间”、“根/虚拟化”);
p->AddParameter(“类”、“Msvm_计算机系统”);
//我们可以添加一个过滤器,只返回有问题的VM,但是
//我在引用时遇到问题,所以选择
//更简单的路线。
系统::集合::对象模型::集合^result=ps->Invoke();
System::String ^s=gcnewsystem::String(id.c_str());
对于(int i=0;iCount;i++){
if(System::String::Compare(动态_cast(结果[i]->Members[“Name”]->Value),s)==0){
//现在怎么办?我想在这个VM上调用RequestStateChange方法
回来
}
}

为什么要使用PowerShell查询WMI您可以使用托管类:

ManagementObjectSearcher ComputerInfos = new ManagementObjectSearcher("select * from Win32_ComputerSystem");

我知道这有点陈腐,但我在C#中遇到了类似的问题,发现这个主题是唯一描述我问题的主题。我得到的解决方案非常基本,这也难怪我是PowerShell的初学者。我希望这也能回答任何可能在这里遇到问题的人的问题

PSObject具有用于访问底层对象的.BaseObject属性。因此,如果您知道具有所需方法的对象的类型(您可能知道,否则我不确定您如何期望任何特定方法),您可以尝试强制转换

SomeClass x = result[i].BaseObject as SomeClass;
if (x == null) 
{
   //some handling
}
x.SpecificMethod();
这是C#casting,但你明白了


希望这有帮助。

最初的原因是为了使它更容易开发,因为这是我们第一次使用托管C++(我们是真正的跨平台C++的家伙)。当我发现我们使用的非托管代码的潜在问题时,使用有芒代码的驱动力消失了(我们在做的事情中没有很多例子)。谢谢