Search code examples
windowspowershell

How to detect the time of last boot in a powershell script?


How do I get the most recent windows boot time in a powershell script?

Currently I'm using this line

Get-WmiObject win32_operatingsystem -ComputerName myserver | Select-Object @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}

It works (in the sense that it returns a valid date) but the date doesn't appear to be sensible.

Background - I've just shut down the server for 5 minutes in expectation of a brief power outage, after re-booting the above expression returns 11/12/2024 03:31:04 (or about 2 weeks ago).

This date may (or may not) be a boot time, but it's definitely not the last reboot I did a few hours ok. So, either this is returning something other than the boot time, OR a brief power-down doesn't count as a re-boot (somehow).

Any ideas?

UPDATE... Ok, I've tried the following

(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime

and

Get-CimInstance -ClassName win32_operatingsystem | select csname, lastbootuptime

They all give me the same two-week-old boot date.

I think the true question is really why wasn't the re-boot recorded in the event logs.


Solution

  • Instead of Get-WmiObject, which is deprecated, use this:

    $lastBoot = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime