如何检索某种类型的CimInstance属性?

问题描述:

所以,我一直在寻找一段时间,我似乎无法找到似乎(至少对我来说)一个简单的基础C#问题的答案。如何检索某种类型的CimInstance属性?

为了进行设置,我组建了一个C#GUI程序,利用远程机器的CIM类检索有关所述机器的数据,该数据将用于从最终用户支持技术人员的角度确定其当前“状态”看法。

我曾与CIM会话建立到远程机器和检索我要求通过查询实例的数据没有问题。我遇到的问题是,我似乎无法弄清楚如何从这些实例中的某个属性中检索值,并返回某个预期类型的​​值。在编译和执行代码之前,如果没有实际运行查询,IDE(Visual Studio 2017)会假定返回值是超级类型“对象”(请原谅任何本地问题)。

这里是我使用供参考代码:

public class DispRecord 
{ 
    //declare properties for record object 
    public string Hostname; 
    public string Status; 
    public string User; 
    public string NTLogin; 
    public string LockTime; 
    public string LockDuration; 
    public string LogonTime; 
    public string LogonDuration; 
    public string LastRestart; 
    public string PwrOnDuration; 
} 

我已包含该特性的构造的自定义类对象我检索和计算。

此自定义对象随后被传递到执行查询和指派的值的属性的功能。我的方法类有几种方法,但这里是一个目前的症结所在:

//method for gathering CIM data 
public static DispRecord QueryCIMData (DispRecord Record) 
{ 
    //use cimsession to remote host 
    using (CimSession Session = CimSession.Create(Record.Hostname, new DComSessionOptions())) 
    { 
     //declare queries 
     string PwrQuery = "Select LastBootUpTime from CIM_OperatingSystem"; 
     //string ProcQuery = "Select CreationDate,Caption from CIM_Process where Name='explorer.exe' or Name='logonui.exe'"; 

     //declare namespace 
     string Namespace = @"root\cimv2"; 

     //perform PwrQuery and retrieve lastbootuptime 
     IEnumerable<CimInstance> Results = Session.QueryInstances(Namespace, "WQL", PwrQuery); 
     DateTime LastBootUpTime = DateTime.Parse(Results.First().CimInstanceProperties["LastBootUpTime"].Value.ToString()); 

     //add PwrOnDuration and LastRestart to Record 
     Record.LastRestart = LastBootUpTime.ToString(); 
     Record.PwrOnDuration = (DateTime.Now - LastBootUpTime).ToString(@"dd\/hh\:mm\:ss"); 
    } 

    //return changed record object 
    return Record; 
} 

以上你看到的是什么工作,但我觉得有必要实现正确的输出的代码回旋是有点可笑我觉得必须有另一种可能更简单或更简洁的方式来达到我想要的效果。当然,有一种更好的方法来检索我期望的DateTime对象,而不是从DateTime对象构造的字符串中检索属性值,然后将其解析为新的Datetime对象,特别是考虑到我正在转身并将其转换回来成一个字符串插入到记录中。

理想情况下,我想这样做,但我不知道如何实现它:

DateTime LastBootUpTime = Results.First().CimInstanceProperties["LastBootUpTime"].Value; 

当我尝试上述情况,编译器会抛出异常,说明它不能隐将类型'Object'的值转换为类型'DateTime'

本质上,由于直到运行时才执行查询,因此返回的CIM实例属性只是作为对象而不是基于类的预期输出该实例是从(在这种情况下,“DateTime”对象预期为“LastBootUpTime”的值)属性)。

的代码不知道什么是未来出了蛋孵化它之前,即使不MSDN。

谁能帮我解决这个看似简单的问题吗?

好了,一些试验和错误之后,我发现最简单的办法,我肯定存在。

要与编译器的工作,到Convert.ToDateTime()方法调用允许代码编译并没有出现异常运行时抛出。

//perform PwrQuery and retrieve lastbootuptime 
IEnumerable<CimInstance> Results = Session.QueryInstances(Namespace, "WQL", PwrQuery); 
DateTime LastBootUpTime = Convert.ToDateTime(Results.First().CimInstanceProperties["LastBootUpTime"].Value); 

//add PwrOnDuration and LastRestart to Record 
Record.LastRestart = LastBootUpTime.ToString(); 
Record.PwrOnDuration = (DateTime.Now - LastBootUpTime).ToString(@"dd\/hh\:mm\:ss"); 

唯一的成本是几 “卫生署!” S :)