【问题标题】:WMI Type Mismatch when assigning CIM_DATETIME分配 CIM_DATETIME 时 WMI 类型不匹配
【发布时间】:2017-08-11 15:08:36
【问题描述】:

我认为我遇到的问题是 CIM_DATETIME 和 DateTime 之间的类型不匹配。

下面是通用服务器类中的一个函数。在调用此函数时,我已经创建了一个 ManagementScope 对象并通过测试 WMI 查询来验证连接。

public void Sync() 
{
    ManagementPath path = new ManagementPath("Win32_OperatingSystem=@");
    ManagementObject classInstance = new ManagementObject(this.Scope, path, null);
    ManagementBaseObject inParams = classInstance.GetMethodParameters("SetDateTime");
    inParams["LocalDateTime"] = "20170811101838.000000+000";
    ManagementBaseObject outParams = classInstance.InvokeMethod("SetDateTime", inParams, null);
    Console.WriteLine(outParams["ReturnValue"]);
}

当我尝试为“LocalDateTime”属性赋值时,我遇到了类型不匹配异常。

如果我尝试获取 inParams["LocalDateTime"] 的类型,则会导致空引用异常。这让我相信 LocalDateTime 不是一个有效的索引,或者它只是引用了一个空对象。

但是,通过枚举其属性,我可以看到 LocalDateTime 是 inParams 的属性。

foreach (var prop in inParams.Properties)
{
    Console.WriteLine($"IsArray : {inParams.IsArray}");
    Console.WriteLine($"IsLocal : {inParams.IsLocal}");
    Console.WriteLine($"Name    : {inParams.Name}");
    Console.WriteLine($"Origin  : {inParams.Origin}");
    Console.WriteLine($"Type    : {inParams.Type}");
    Console.WriteLine($"Value   : {inParams.Value}");
 }

这将返回以下内容,

IsArray : False
IsLocal : False
Name    : LocalDateTime
Origin  : __PARAMETERS
Type    : DateTime
Value   : 

所以,我的问题是

  1. 如何正确引用Win32_OperatingSystem类的SetDateTime方法的LocalDateTime参数?

  2. 是否可以转换为CimType.DateTime

【问题讨论】:

    标签: c# wmi


    【解决方案1】:

    如果将来有人偶然发现这个......

    我需要使用 ManagementDateTimeConverter.ToDmtfDateTime 方法将 System.DateTime 转换为 DMTF 日期时间。

    inParams["LocalDateTime"] = ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now);

    反之,从 DMTF 日期时间到 System.DateTime 需要使用 ManagementDateTimeConverter.ToDateTime 方法。

    var systemDateTime = ManagementDateTimeConverter.ToDateTime("20170811101838.000000+000");

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 2019-08-10
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 2015-01-18
      相关资源
      最近更新 更多