C ++ WMI执行对象的方法

时间:2018-01-28 14:03:28

标签: python c++ wmi getmethod

我正在尝试从C ++执行Delete对象的CIM_DataFile方法

我能够在python中完成它而没有任何问题:

import wmi

c = wmi.WMI()
result = c.query("SELECT * FROM CIM_DataFile WHERE Name = \"C:\\deleteme.txt\"")
for file_ in result:
    file_.Delete()

可悲的是,它在C ++中要复杂得多。

我能够获得对象本身,但不知道如何从这里继续。

任何帮助都会受到赞赏。

到目前为止我的代码:

#include <Windows.h>  
#include <iostream>  
#include <WbemCli.h>  

#pragma comment(lib, "wbemuuid.lib")  

int main()
{
    using std::cout;
    using std::cin;
    using std::endl;

    HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    if (FAILED(hRes))
    {
        cout << "Unable to launch COM: 0x" << std::hex << hRes << endl;
        return 1;
    }

    if ((FAILED(hRes = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0))))
    {
        cout << "Unable to initialize security: 0x" << std::hex << hRes << endl;
        return 1;
    }

    IWbemLocator* pLocator = NULL;
    if (FAILED(hRes = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pLocator))))
    {
        cout << "Unable to create a WbemLocator: " << std::hex << hRes << endl;
        return 1;
    }

    IWbemServices* pService = NULL;
    if (FAILED(hRes = pLocator->ConnectServer(L"root\\CIMV2", NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &pService)))
    {
        pLocator->Release();
        cout << "Unable to connect to \"CIMV2\": " << std::hex << hRes << endl;
        return 1;
    }

    IEnumWbemClassObject* pEnumerator = NULL;
    if (FAILED(hRes = pService->ExecQuery(L"WQL", L"SELECT * FROM CIM_DataFile WHERE Name = \"C:\\\\deleteme.txt\"", WBEM_FLAG_FORWARD_ONLY, NULL, &pEnumerator)))
    {
        pLocator->Release();
        pService->Release();
        cout << "Unable to retrive CIM_DataFile: " << std::hex << hRes << endl;
        return 1;
    }

    IWbemClassObject* clsObj = NULL;
    int numElems;
    while ((hRes = pEnumerator->Next(WBEM_INFINITE, 1, &clsObj, (ULONG*)&numElems)) != WBEM_S_FALSE)
    {
        if (FAILED(hRes))
            break;

        IWbemClassObject* pInParamsDefinition = NULL;
        clsObj->GetMethod(L"Delete", 0, &pInParamsDefinition, NULL);

        clsObj->Release();
    }

    pEnumerator->Release();
    pService->Release();
    pLocator->Release();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

尝试以下方式:

使用pService对象使用方法DeleteInstance。

e.g。

_bstr_t objPath(L"CIM_DataFile.Name='file_to_delete'"); \\ insert name\path properly
HRESULT res = pService->DeleteInstance(objPath,0,NULL,NULL);