You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C++中获取PowerShell Invoke返回值及创建PSObject集合报错求助

问题解决:C++/CLI调用PowerShell无法获取Invoke返回集合

错误原因分析

你遇到的编译错误核心来自两个问题:

  • 缺失命名空间:Collection<T> 属于 System::Collections::ObjectModel 命名空间,代码未引入该命名空间,导致编译器无法识别类型。
  • 托管类型声明错误:C++/CLI中所有.NET引用类型必须用^声明(等价于C#的引用),直接写Collection<PSObject>会被当作值类型处理,不符合.NET类型规则。

另外获取PSVersion的代码逻辑错误:AddCommand仅支持添加单一命令名,不能直接传入表达式字符串;直接调用ToString()只能得到PowerShell对象的类型字符串,不是执行结果。

修复后的代码

#include <vcclr.h>
#include <Windows.h>
#include <iostream>
#using <mscorlib.dll>
#using <System.dll>
#include <vector>
#using <System.Management.Automation.dll>
using namespace std;

using namespace System;
using namespace System::Management::Automation;
// 引入缺失的命名空间
using namespace System::Collections::ObjectModel;

void RunPowerShell()
{
    // 正确声明托管集合类型:Collection<PSObject^>^
    Collection<PSObject^>^ powObject = PowerShell::Create()->AddScript(gcnew String("Get-WmiObject -Query \"select * from win32_bios\""))->Invoke();
    
    // 遍历集合提取BIOS属性值
    for each (PSObject^ item in powObject)
    {
        Console::WriteLine("BIOS版本: {0}", item->Properties["SMBIOSBIOSVersion"]->Value);
        Console::WriteLine("厂商: {0}", item->Properties["Manufacturer"]->Value);
    }

    // 正确获取PowerShell版本的逻辑
    Collection<PSObject^>^ versionResult = PowerShell::Create()->AddScript(gcnew String("(Get-Variable PSVersionTable -ValueOnly).PSVersion"))->Invoke();
    if (versionResult->Count > 0)
    {
        String^ s = versionResult[0]->ToString();
        // 转换为宽字符输出
        pin_ptr<const wchar_t> wch = PtrToStringChars(s);
        wprintf(L"%s\n", wch);
    }
}

int main()
{
    RunPowerShell();
    return 0;
}

关键修复点说明

  1. 补全命名空间:添加using namespace System::Collections::ObjectModel;,让编译器识别Collection<T>类型。
  2. 修正托管类型声明:将Collection<PSObject>改为Collection<PSObject^>^,符合C++/CLI对.NET引用类型的声明规则,^表示这是一个托管对象引用。
  3. 修复版本获取逻辑:用AddScript执行表达式,调用Invoke()获取结果集合,再从集合中取出第一个元素转换为字符串。
  4. 添加结果遍历示例:演示如何从返回的PSObject集合中提取具体属性值。

编译注意事项

确保项目为C++/CLI项目(非纯C++项目),且System.Management.Automation.dll的引用路径正确(通常位于PowerShell安装目录,如C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35)。

内容的提问来源于stack exchange,提问作者Vineeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:25:34