时间格式转换

在WMI中使用Win32_NTLogEvent查询出来的日志生成时间timegenerated类似于“20130820162350.350000+480“,这种时间格式很特殊,经查是DMTF时间格式字符串,在PowerShell中与其它时间类型进行比较就需要对其进行转换,将DMTF字符串转DateTime类型。

转换的方案有两种:
 
1)采用.NET 2.0中的System.Management.ManagementDateTimeConverter类
该类位于system.management.dll动态链接库中,使用时需要先加载,代码如下:
[void][Reflection.Assembly]::LoadFile("c:windowsmicrosoft.netframeworkv2.0.50727system.management.dll")
gwmi win32_ntlogevent -Filter "logfile='application' and sourcename='db2' " -Property timegenerated,message -com $ip|
select Message,@{Name="LogTime";Expression={[System.Management.ManagementDateTimeConverter]::ToDateTime($_.Timegenerated)}}|
sort LogTime -desc
 
2)使用事件对象的扩展方法 ConvertToDateTime
gwmi -q "SELECT timegenerated FROM win32_ntlogevent WHERE logfile='application' and sourcename='db2'"|%{$_.ConvertToDateTime($_.Timegenerated)}
原文地址:https://www.cnblogs.com/IvanChen/p/4492358.html