开发者

How to invoke method on PSObject from managed C++

开发者 https://www.devze.com 2023-04-10 15:26 出处:网络
I\'m trying to execute a WMI function using the PowerShell class from a managed C++ function. But I can\'t work out how to call a method on the object that is returned in the PSObject list from the P

I'm trying to execute a WMI function using the PowerShell class from a managed C++ function.

But I can't work out how to call a method on the object that is returned in the PSObject list from the PowerShell.Invoke() method.

(On the command line I would just do (gwmi ....).RequestStateChange(2) - but I can't see how to add the () using the few methods of the PowerShell class.

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 proble开发者_StackOverflow社区ms 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;
    }
}


Why do you want to us PowerShell to query WMI you can use managed class ManagementObjectSearcher for that :

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


I know this is a bit stale, but I had similar problem in C# and found this topic as only one describing my problem. The solution I got is pretty basic, which is no wonder since I am beginner with PowerShell. I hope this would answer this problem as well to anyone that may stumble here.

PSObject has .BaseObject property that is used to access underlying object. So if you know the type of the object that has desired method (which you probably do, otherwise I'm not sure how can you expect any specific method), you can simply try casting.

SomeClass x = result[i].BaseObject as SomeClass;
if (x == null) 
{
   //some handling
}
x.SpecificMethod();

This is C# casting, but you get the idea.

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消