TOGEEK
TOGEEK

Reputation: 741

converting datetime from wmiobject to datetime

Trying to get the difference in days between to dates: Today's date. and a date/time from a wmiobject (this was taken from a post from the PendingReboot script from Hey, Scripting! blog):

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

The result of $Today is

09/06/2016

and $Lastreboottime is

05/05/2016 11:13:21 

So I want to get rid of the time but not sure how to do this.

Secondly, I get this error if I were to run the script, though I guess this may go away if I am able to extract the date only in $Lastreboot

Cannot convert the "@{csname=JDWTAWEB1; LastBootUpTime=05/05/2016 11:13:21}" value of type "Selected.System.Management.ManagementObject" to type "System.DateTime".

Any ideas?

Upvotes: 0

Views: 13199

Answers (3)

Frode F.
Frode F.

Reputation: 54881

  1. Remove -Format d and compare the Date-properties of the DateTime-objects to get the days-diff only.
  2. Your $Lastreboottime-variable references an object with both computername csname and the LastBootUpTime, so you need to access the LastBootUpTime

Try:

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

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

$DiffDays.TotalDays
13

Upvotes: 3

Trey Nuckolls
Trey Nuckolls

Reputation: 591

I think that the WMIObject conversion might need to get to a Datetime object by way of a properly formatted string. I did this (minus the -Computername $Computer part) and it seemed to work.

[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

Upvotes: 1

beatcracker
beatcracker

Reputation: 6920

  1. Remove -Format d from Get-Date. You need DateTime object, not a string.
  2. $Lastreboottime is an object with 2 properties: csname and lastbootuptime. You have to use lastbootuptime property.

Example:

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

Upvotes: 0

Related Questions