1

我正在尝试从 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;
}
4

1 回答 1

0

尝试以下方式:

使用 pService 对象使用方法 DeleteInstance。

例如

_bstr_t objPath(L"CIM_DataFile.Name='file_to_delete'"); \\ insert name\path properly
HRESULT res = pService->DeleteInstance(objPath,0,NULL,NULL);
于 2018-03-27T05:24:07.107 回答