【问题标题】:How to invoke method on PSObject from managed C++如何从托管 C++ 调用 PSObject 上的方法
【发布时间】:2011-10-01 22:28:21
【问题描述】:

我正在尝试使用托管 C++ 函数中的 PowerShell 类执行 WMI 函数。

但我不知道如何调用从 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;
    }
}

【问题讨论】:

    标签: .net c++ powershell wmi


    【解决方案1】:

    你为什么要我们 PowerShell 来查询 WMI 你可以使用托管类 ManagementObjectSearcher

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

    【讨论】:

    • 最初的原因是为了让开发更容易,因为这是我们第一次使用托管 C++(我们真的是跨平台的 C++ 人)。当我发现我们使用的非托管代码存在潜在问题时,使用托管代码的动力就消失了。 (我们正在做的事情并没有很多例子)。谢谢。
    【解决方案2】:

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

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

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

    这是 C# 转换,但你明白了。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-03-24
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      相关资源
      最近更新 更多