Back in the day, Microsoft had a utility (uptime.exe) which was incredibly useful when managing many servers. It showed how many days the computer had been running since its last boot. This is particularly useful when troubleshooting issues.
Up until PowerShell 6.0, this was not available natively as a cmdlet. Sure, you could use a WMI cmdlets to get the last boot entry, but you then had to convert it to DateTime object and use math – not ideal when troubleshooting. So, I wrote this script to help get the last boot time on any windows computer that has older versions of PowerShell. One feature this script has over Microsoft’s is that you can specify a remote computer. It uses WMI, so if you allow WinRM, then this should work.
You can either use the script (.ps1) or copy the code as a function into your windows PowerShell profile (see code below). I personally have it in my windows PowerShell profile, that way it loads every time I open a new console.
Script available here: Get-Uptime
<####################################################################################
Author: Tino Hernandez
Version: 1.0
Date: 03/15/2021
.SYNOPSIS
This cmdlet returns the time elapsed since the last boot of the operating system.
The Microsoft Get-Uptime cmdlet was introduced in PowerShell 6.0, however you
can use this script on older versions of PowerShell. For more
information on Microsoft cmdlet, see the following link.
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-uptime
.DESCRIPTION
This cmdlet returns the time elapsed since the last boot of the operating system.
Additionally, this can also retrieve from remote computer.
.PARAMETER ComputerName
Required : No
DataType : String
Description : This will be used to specify the computer name. If blank, it will be
set to $env:COMPUTERNAME
.PARAMETER Since
Required : No
DataType : Switch
Description : this will return a DateTime object representing the last time that the
computer was booted.
.EXAMPLE
Get-Uptime
Get-Uptime -Since
Get-Uptime -ComputerName Server01 -Since
#######################################################################################>
Function Get-Uptime{
Param(
[Parameter(Mandatory=$false)]
[string]$ComputerName,
[Parameter(Mandatory=$false)]
[switch]$Since
)
# Check if computer name is supplied, if not set default to local machine
IF([string]::IsNullOrEmpty($ComputerName)){
$ComputerName = $env:COMPUTERNAME
}
# Calculate last boot time
IF($Since.IsPresent){
[System.Management.ManagementDateTimeconverter]::ToDateTime($(Get-WmiObject -ComputerName $ComputerName -Class Win32_OperatingSystem | Select-Object -ExpandProperty LastBootUpTime))
}ELSE{
(Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($(Get-WmiObject -ComputerName $ComputerName -Class Win32_OperatingSystem | Select-Object -ExpandProperty LastBootUpTime)) #| FT Days,Hours,Minutes,Seconds -AutoSize
}
}