在 C++ 中从 WMI(Win32_LogicalDisk 类)调用 Chkdsk ->“参数无效”

2023-12-20

我正在尝试从 C++ 中的 WMI 运行 Chkdsk(我正在使用 Qt Framework)。 “ExecMethod”返回“参数无效”。 我已经根据设置参数http://msdn.microsoft.com/en-us/library/cc250766.aspx http://msdn.microsoft.com/en-us/library/cc250766.aspx-> 我正在使用半同步调用。

我正在使用 MSDN 文档(Win32_LogicalDisk、WMI C++ 应用程序示例、Win32_Volume,...)

我也尝试过 Win32_Volume 但效果不佳。

我的部分代码:

IWbemLocator *pLoc = NULL;
HRESULT hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);

IWbemServices *pSvc = NULL;
hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);

BSTR MethodName = SysAllocString(L"Chkdsk");
BSTR ClassName = SysAllocString(L"Win32_LogicalDisk");
IWbemCallResult *pCallRes = 0;
hres = pSvc->ExecMethod(ClassName, MethodName, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL,  NULL, NULL, &pCallRes);

我也尝试过:

BSTR ClassName = SysAllocString(L"Win32_LogicalDisk.DeviceID='C:'"); 

但也存在同样的问题。

欢迎任何帮助。


您没有向 classname 参数传递正确的值

你必须使用类似的东西L"Win32_LogicalDisk.DeviceID=\"C:\""

无论如何,这是一个完整的示例控制台应用程序。

#include "stdafx.h"
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
# pragma comment(lib, "wbemuuid.lib")

//CREDENTIAL structure
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788%28v=vs.85%29.aspx
#define CRED_MAX_USERNAME_LENGTH            513
#define CRED_MAX_CREDENTIAL_BLOB_SIZE       512
#define CREDUI_MAX_USERNAME_LENGTH CRED_MAX_USERNAME_LENGTH
#define CREDUI_MAX_PASSWORD_LENGTH (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2)


#pragma argsused
int main(int argc, char* argv[])
{
    wchar_t pszName[CREDUI_MAX_USERNAME_LENGTH+1] = L"user";
    wchar_t pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1]  = L"password";
    BSTR strNetworkResource;
    //To use a WMI remote connection set localconn to false and configure the values of the pszName, pszPwd and the name of the remote machine in strNetworkResource
    bool localconn = true;  
    strNetworkResource = localconn ?  L"\\\\.\\root\\CIMV2" : L"\\\\remote--machine\\root\\CIMV2";

    COAUTHIDENTITY *userAcct =  NULL ;
    COAUTHIDENTITY authIdent;
    HRESULT hres;

    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
        cout << _com_error(hres).ErrorMessage() << endl;
        cout << "press enter to exit" << endl;
        cin.get();          
        return 1;                  // Program has failed.
    }

    // Set general COM security levels --------------------------
    if (localconn)
        hres =  CoInitializeSecurity(
            NULL,
            -1,                          // COM authentication
            NULL,                        // Authentication services
            NULL,                        // Reserved
            RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
            RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
            NULL,                        // Authentication info
            EOAC_NONE,                   // Additional capabilities
            NULL                         // Reserved
            );
    else
        hres =  CoInitializeSecurity(
            NULL,
            -1,                          // COM authentication
            NULL,                        // Authentication services
            NULL,                        // Reserved
            RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
            RPC_C_IMP_LEVEL_IDENTIFY,    // Default Impersonation
            NULL,                        // Authentication info
            EOAC_NONE,                   // Additional capabilities
            NULL                         // Reserved
            );


    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x" << hex << hres << endl;
        cout << _com_error(hres).ErrorMessage() << endl;
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();          
        return 1;                      // Program has failed.
    }

    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;
    hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);

    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object. " << "Err code = 0x" << hex << hres << endl;
        cout << _com_error(hres).ErrorMessage() << endl;
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();              
        return 1;                 // Program has failed.
    }

    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;

    // Connect to the root\\CIMV2 namespace
    // and obtain pointer pSvc to make IWbemServices calls.
    if (localconn)  
        hres = pLoc->ConnectServer(
             _bstr_t(strNetworkResource),      // Object path of WMI namespace
             NULL,                    // User name. NULL = current user
             NULL,                    // User password. NULL = current
             0,                       // Locale. NULL indicates current
             NULL,                    // Security flags.
             0,                       // Authority (e.g. Kerberos)
             0,                       // Context object
             &pSvc                    // pointer to IWbemServices proxy
             );
    else
        hres = pLoc->ConnectServer(
            _bstr_t(strNetworkResource),  // Object path of WMI namespace
            _bstr_t(pszName),             // User name
            _bstr_t(pszPwd),              // User password
            NULL,                // Locale
            NULL,                // Security flags
            NULL,                // Authority
            NULL,                // Context object
            &pSvc                // IWbemServices proxy
            );


    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x" << hex << hres << endl;
        cout << _com_error(hres).ErrorMessage() << endl;
        pLoc->Release();
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();                  
        return 1;                // Program has failed.
    }

    cout << "Connected to root\\CIMV2 WMI namespace" << endl;

    // Set security levels on the proxy -------------------------
    if (localconn)
        hres = CoSetProxyBlanket(
           pSvc,                        // Indicates the proxy to set
           RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
           RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
           NULL,                        // Server principal name
           RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx
           RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
           NULL,                        // client identity
           EOAC_NONE                    // proxy capabilities
        );
    else
    {
        // Create COAUTHIDENTITY that can be used for setting security on proxy
        memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
        authIdent.PasswordLength = wcslen (pszPwd);
        authIdent.Password = (USHORT*)pszPwd;
        authIdent.User = (USHORT*)pszName;
        authIdent.UserLength = wcslen(pszName);
        authIdent.Domain = 0;
        authIdent.DomainLength = 0;
        authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
        userAcct = &authIdent;

        hres = CoSetProxyBlanket(
           pSvc,                           // Indicates the proxy to set
           RPC_C_AUTHN_DEFAULT,            // RPC_C_AUTHN_xxx
           RPC_C_AUTHZ_DEFAULT,            // RPC_C_AUTHZ_xxx
           COLE_DEFAULT_PRINCIPAL,         // Server principal name
           RPC_C_AUTHN_LEVEL_PKT_PRIVACY,  // RPC_C_AUTHN_LEVEL_xxx
           RPC_C_IMP_LEVEL_IMPERSONATE,    // RPC_C_IMP_LEVEL_xxx
           userAcct,                       // client identity
           EOAC_NONE                       // proxy capabilities
        );
    }


    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
        cout << _com_error(hres).ErrorMessage() << endl;
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();                  
        return 1;               // Program has failed.
    }

    // Use the IWbemServices pointer to make requests of WMI ----

    BSTR MethodName = SysAllocString(L"Chkdsk");
    BSTR ClassName = SysAllocString(L"Win32_LogicalDisk");

    IWbemClassObject* pClass = NULL;
    hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);

    IWbemClassObject* pInParamsDefinition = NULL;
    hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL);

    IWbemClassObject* pClassInstance = NULL;
    hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);

    VARIANT varCommand;


    // Execute Method
    IWbemClassObject* pOutParams = NULL;
    hres = pSvc->ExecMethod(L"Win32_LogicalDisk.DeviceID=\"C:\"", MethodName, 0,
    NULL, pClassInstance, &pOutParams, NULL);

    if (FAILED(hres))
    {
        cout << "Could not execute method. Error code = 0x" << hex << hres << endl;
        cout << _com_error(hres).ErrorMessage() << endl;        
        SysFreeString(ClassName);
        SysFreeString(MethodName);
        if (pClass) pClass->Release();
        if (pInParamsDefinition) pInParamsDefinition->Release();
        if (pOutParams) pOutParams->Release();
        if (pSvc) pSvc->Release();
        if (pLoc) pLoc->Release();     
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();          
        return 1;               // Program has failed.
    }


    VARIANT varReturnValue;
    hres = pOutParams->Get(L"ReturnValue", 0, &varReturnValue, NULL, 0);
    if (!FAILED(hres))
    wcout << "ReturnValue " << varReturnValue.intVal << endl;
    VariantClear(&varReturnValue);


    // Clean up    
    SysFreeString(ClassName);
    SysFreeString(MethodName);  
    if (pClass) pClass->Release();
    if (pInParamsDefinition) pInParamsDefinition->Release();
    if (pOutParams) pOutParams->Release();
    if (pLoc) pLoc->Release();
    if (pSvc) pSvc->Release();
    CoUninitialize();
    cout << "press enter to exit" << endl;
    cin.get();  
    return 0;
}

如果您不熟悉 WMI 和 C++,您可以尝试以下工具WMI Delphi Code Creator https://code.google.com/p/wmi-delphi-code-creator/它可以帮助您创建 C++ 代码来访问 WMI。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C++ 中从 WMI(Win32_LogicalDisk 类)调用 Chkdsk ->“参数无效” 的相关文章

随机推荐

  • Internet Explorer 9 中 URL 查询字符串值的 UTF-8 字符编码问题

    当尝试显示 URL 查询字符串中提供的特殊字符 德语重音字符 时 我在 Internet Explorer 特别是 IE9 中发现了一个奇怪的问题 这在 Firefox 和 Chrome 中按预期工作 例如 我正在使用的 URL 看起来像这
  • 运行 spring boot jar 时无法找到或加载主类

    我在运行通过 mvn package 创建的 jar 时遇到问题 我尝试了各种解决方案但没有成功 pom xml
  • Spark 如何与 CPython 互操作

    我有一个用 Akka 编写的系统scala需要呼吁一些人Python代码 依赖于Pandas and Numpy 所以我不能只使用 Jython 我注意到 Spark 在其工作节点上使用 CPython 所以我很好奇它如何执行 Python
  • /lib64/libc.so.6:找不到版本“GLIBC_2.32”

    我正在使用基本示例在 Ubuntu 上构建 lambda 它构建时没有任何错误 但如果我在 aws 上上传并测试它 则会崩溃 errorMessage RequestId 7f4d0aca 125c 4032 98dd 9ff387e525
  • 如何在tomcat服务器上部署reactJS应用程序?

    我正在尝试构建一个 ReactJS 应用程序 我想将其托管在 tomcat 服务器上 我已经使用了命令 npm run build 并且构建已准备就绪 我应该在 Tomcat 服务器中的哪里复制这些文件 我是否需要创建另一个应用程序并将其部
  • Hibernate Inverse 属性

    我正在创建一对多关系 所以 我有父母和孩子 级联属性设置为全部 我想知道 我们是否考虑以下代码 Parent p Parent session load Parent class pid Child c new Child child el
  • Material-ui:如何停止嵌套组件中单击事件的传播

    我有一个IconMenu里面的组件Paper成分 我想阻止内部组件 IconMenu 这就是我想出来的 没有显着的结果 我也尝试用 onClick 代替onTouchTap onMouseUp具有相同的效果 iconMenuClick方法从
  • Java:递增/递减运算符的前缀/后缀

    从下面的程序或here http download oracle com javase tutorial java nutsandbolts examples PrePostDemo java 为什么最后一个调用System out pri
  • 如何移动 JPanel

    我有一个JDialog其中包含JPanel和其他元素 例如JTextField 我想搬家JDialog加载到屏幕上后从一个位置到另一个位置 当我尝试使用时jdialog setLocation 我无法动弹JDialog并且添加到其中的所有其
  • 多个使用者和查询 C# BlockingCollection

    我使用 NET 4 0 BlockingCollection 来处理一个项目队列 每个项目都需要通过一个操作来处 理 该操作最多需要一秒钟来处理每个项目 该项目队列可以由不同的线程添加到该队列中 我对此有几个问题 a 允许多个消费者处理此
  • 如何确定某个日期是否位于当前星期的日期之间?

    In C 我们如何检查特定日期与周内日期 例如 2014 年 6 月 2 日 当前几周 2014年2月2日 2014年2月8日 所以这个日期是在上周 使用它进行检查 如果您希望从 fromDate 开始始终是 1 周 则最后一个参数是可选的
  • 消除 BigQuery 表中的重复记录

    我计划每天将增量数据附加到 BigQuery 表中 每次我向现有表添加增量数据时 我都想从表中的现有数据中消除重复记录 基于主键列 一种方法是 从增量数据中收集密钥集 我们称其为INCR KEYS 对以下行运行查询 SELECT all c
  • 将 mkv 转换为 h264 FFmpeg

    EDIT 这个问题已经变得非常流行 并且是搜索 convert mkv to h264 ffmpeg 的最佳结果之一 因此我认为对于任何偶然发现这个问题的人来说 添加这一点是适当的 而不是使用 ffmpeg i input mkv c v
  • C# Outlook 2007 - 如何直接从我的插件访问附件内容?

    我正在尝试解析基于文本的文件附件 txt doc 等 但是 我似乎无法获取二进制信息本身 我可以获取文件名 也可以将文件保存到某个临时文件夹并从那里打开它 但这看起来很混乱 有没有什么方法可以访问附件的内容而不保存它 阅读它 然后删除它 或
  • 使用 Visual Studio 管理源代码管理中的引用

    我在 Visual Studio 项目中管理 dll 引用时遇到问题 所有注册的 NET 和 COM 引用都工作正常 但当涉及磁盘上的 dll 文件时 如果我引用磁盘上的文件 我的同事将丢失引用 因为他们可能将其放在磁盘上的不同位置等 Vi
  • 如何使用layoutIfNeeded?

    何时以及如何layoutIfNeeded用过的 我知道当我们改变视图的布局时 我们可以调用setNeedsLayout更新布局但不确定何时layoutIfNeeded应该使用 注意 我有layoutIfNeeded在实际代码中使用但忘记了它
  • 无法在iOS中将统一的CNContact添加到CNGroup中

    这就是我正在做的 void doCreateGroup self contentView endEditing true NSString newString self contentView groupNameField text str
  • 检索 SQLite 中所有项目的最快方法是什么?

    我在 Windows 上编程 我将信息存储在 sqlite 中 然而我发现获取所有物品有点慢 我正在使用以下方式 select from XXX 检索 1 7MB SQLite DB 中的所有项目大约需要 200 400 毫秒 太慢了 有人
  • 在 NodeJS 中可靠地读取 FIFO

    我正在编写一个与第三方应用程序交互的 NodeJS 脚本 第三方应用程序将在文件打开期间将数据写入文件 我希望我的 NodeJS 应用程序能够实时接收这些数据 我的脚本创建一个 fifo child process spawnSync mk
  • 在 C++ 中从 WMI(Win32_LogicalDisk 类)调用 Chkdsk ->“参数无效”

    我正在尝试从 C 中的 WMI 运行 Chkdsk 我正在使用 Qt Framework ExecMethod 返回 参数无效 我已经根据设置参数http msdn microsoft com en us library cc250766