将日期时间从 wmiobject 转换为日期时间

converting datetime from wmiobject to datetime

正在尝试获取日期之间的天数差异:今天的日期。和来自 wmiobject 的 date/time(这是从 Hey, Scripting! 博客的 PendingReboot 脚本中获取的 post):

$Lastreboottime = Get-WmiObject win32_operatingsystem -ComputerName $Computer | 
select csname, @{LABEL='LastBootUpTime';EXPRESSION=$_.ConverttoDateTime($_.lastbootuptime)}} 
$Today = Get-Date -Format d
$DiffDays = $Today - $Lastreboottime 

$今天的结果是

09/06/2016

$Lastreboottime 是

05/05/2016 11:13:21 

所以我想摆脱时间,但不知道该怎么做。

其次,如果我要 运行 脚本,我会收到此错误,但我想如果我只能在 $Lastreboot

中提取日期,这可能会消失
Cannot convert the "@{csname=JDWTAWEB1; LastBootUpTime=05/05/2016 11:13:21}" value of type "Selected.System.Management.ManagementObject" to type "System.DateTime".

有什么想法吗?

  1. Get-Date 中删除 -Format d。您需要 DateTime 对象,而不是字符串。
  2. $Lastreboottime 是一个具有 2 个属性的对象:csnamelastbootuptime。你必须使用 lastbootuptime 属性.

示例:

$Today = Get-Date
$DiffDays = $Today - $Lastreboottime.lastbootuptime

我认为 WMIObject 转换可能需要通过格式正确的字符串获取 Datetime 对象。我这样做了(减去 -Computername $Computer 部分)并且它似乎有效。

[string]$BootTimeString=(Get-WmiObject win32_operatingsystem -ComputerName $Computer).lastbootuptime -replace '\..*',''

$BootTimeDT=[datetime]::ParseExact($BootTimeString,'yyyyMMddHHmmss',$null)

$DiffDays = (NEW-TIMESPAN –Start $BootTimeDT –End (Get-Date)).Days
  1. 删除 -Format d 并比较 DateTime 对象的 Date 属性以仅获取天数差异。
  2. 您的 $Lastreboottime-变量引用了一个同时具有计算机名 csnameLastBootUpTime 的对象,因此您需要访问 LastBootUpTime

尝试:

$Lastreboottime = Get-WmiObject win32_operatingsystem | 
select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}

$Today = Get-Date
$DiffDays = $Today.Date - $Lastreboottime.LastBootUpTime.Date

$DiffDays.TotalDays
13