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?
1
Instead of Get-WmiObject, which is deprecated, use this:
$lastBoot = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
I use the following as a uname-like
command. The LastBootUpTime is near the end.
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[string[]] $NetworkPrefixes = @('10','192')
)
$unameInfo = Get-CimInstance Win32_OperatingSystem
$csInfo = Get-CimInstance Win32_ComputerSystem
$unameInfo | Add-Member -NotePropertyName 'UserName' -NotePropertyValue $csInfo.UserName
$unameInfo | Add-Member -NotePropertyName 'TotalPhysicalMemory' `
-NotePropertyValue ('{0:0.##}' -f ($csInfo.TotalPhysicalMemory / 1GB) + ' GiB')
$unameInfo | Add-Member -NotePropertyName 'LogonServer' -NotePropertyValue $Env:LOGONSERVER
$unameInfo | Add-Member -NotePropertyName 'UserDomain' -NotePropertyValue $Env:USERDOMAIN
$DisplayVersion = (Get-Item "HKLM:SOFTWAREMicrosoftWindows NTCurrentVersion").GetValue('DisplayVersion')
if ([string]::IsNullOrWhiteSpace($DisplayVersion)) { $DisplayVersion = 'unknown'}
$unameInfo | Add-Member -NotePropertyName 'DisplayVersion' -NotePropertyValue $DisplayVersion
#$IpAddresses = ((Get-NetIPAddress).IPAddress | Where-Object { ($_ -replace '^([0-9a-fA-F]+).*','$1') -in $NetworkPrefixes }) -join ', '
$IpAddresses = ([System.Net.DNS]::GetHostByName($null)).AddressList.IPAddressToString -join ', '
$unameInfo | Add-Member -NotePropertyName 'IPAddresses' -NotePropertyValue $IpAddresses
$AssetTag = (Get-CimInstance -ClassName Win32_SystemEnclosure).SMBIOSAssetTag
$unameInfo | Add-Member -NotePropertyName 'AssetTag' -NotePropertyValue $AssetTag
$unameInfo | Add-Member -NotePropertyName 'PSVersion' -NotePropertyValue $PSVersionTable.PSVersion.ToString()
$unameInfo | Add-Member -NotePropertyName 'Uptime' -NotePropertyValue ((Get-Date) - $unameInfo.LastBootUpTime).ToString()
$Properties = @('CSName', 'AssetTag', 'IPAddresses', 'UserDomain', 'UserName', 'LogonServer',
'Caption', 'Version', 'PSVersion', 'DisplayVersion',
'BuildType', 'OSArchitecture', 'TotalPhysicalMemory', 'LastBootUpTime', 'Uptime'
)
$unameInfo | Select-Object -Property $Properties #| Format-Table -AutoSize
1