以Win32_NetworkAdapterConfiguration
格式存储来自DateTime
的某些数据时,找到一个好的解决方案有点麻烦。开始烦人了。
有时我遇到无法绑定的错误。有时它说无法转换。
这就是存储在DHCPLeaseObtained
中的内容。微软的课程Website表示已经是DateTime
,但是Get-Member
和.GetType()
则表示它是String
19700101001541.000000-300
在将子字符串弄乱之前和之后,我都尝试将其包装在Get-Date
中,但没有成功。还尝试了以下失败的尝试
$NewDate = [Datetime]::ParseExact(($Configuration_Data[0].DHCPLeaseObtained), 'MM/dd/yyyy', $null)
示例代码以我当前用来使日期可读的复杂方式获取数据
$Adapter_Data = Get-WmiObject Win32_NetworkAdapter |
Where-Object {$_.NetConnectionStatus -EQ 2} |
Select-Object Index
foreach ($Row in $Adapter_Data) {
$Configuration_Data = Get-WmiObject Win32_NetworkAdapterConfiguration |
Where-Object {$_.Index -eq $Row.Index} |
Select-Object DHCPLeaseObtained
}
$Configuration_Data[0].DHCPLeaseObtained
$After = (
$Configuration_Data[0].DHCPLeaseObtained.Substring(0,4) +
$Configuration_Data[0].DHCPLeaseObtained.Substring(4,2) +
$Configuration_Data[0].DHCPLeaseObtained.Substring(6,2) +
$Configuration_Data[0].DHCPLeaseObtained.Substring(8,2) +
$Configuration_Data[0].DHCPLeaseObtained.Substring(10,2)
)
$After
在DateTime
中获得任何更简单解决方案的帮助或想法,将不胜感激。
答案 0 :(得分:0)
您已经看到日期时间格式有点奇怪,“年月日日时分分秒”。。
以这种格式转换日期的最简单方法是使用Win32_OperatingSystem
类,如下所示:
$os = Get-WmiObject –Class Win32_OperatingSystem
$os.ConvertToDateTime($Configuration_Data[0].DHCPLeaseObtained)
您的完整代码段:
$Adapter_Data = Get-WmiObject Win32_NetworkAdapter |
Where-Object {$_.NetConnectionStatus -EQ 2} |
Select-Object Index
foreach ($Row in $Adapter_Data) {
$Configuration_Data = Get-WmiObject Win32_NetworkAdapterConfiguration |
Where-Object {$_.Index -eq $Row.Index} |
Select-Object DHCPLeaseObtained
}
$os = Get-WmiObject –Class Win32_OperatingSystem
$os.ConvertToDateTime($Configuration_Data[0].DHCPLeaseObtained)
默认情况下,它将以以下格式输出日期时间对象:
01 November 2018 13:30:35
输出是有效的日期时间对象:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType
参考:https://blogs.msdn.microsoft.com/richmac/2011/07/21/wmi-date-formats-powershell-to-the-rescue/