0

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?

TOGEEK
  • 711
  • 4
  • 15
  • 34

3 Answers3

2
  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
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • How can we achieve this in below CSV format? Get-WmiObject win32_operatingsystem | ConvertTo-Csv | ConvertFrom-Csv | select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}} – manjesh23 Jan 21 '22 at 08:34
1

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
Trey Nuckolls
  • 581
  • 6
  • 21
0
  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
beatcracker
  • 6,714
  • 1
  • 18
  • 41