Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Scripting Games January 2016: Get-PCBUptime
function Get-PCBUptime {
A simple tool for checking how long a system on the network has been running since last boot.
Get-PCBUptime is a quick WMI-based tool for determinging a remote system's uptime. It is useful for verifying
what a user says when asked if they've rebooted their machine recently, or to generate a report of server uptimes.
Get-PCBUptime is written by and copyright of Christopher R. Lowery, aka The PowerShell Bear (; Twitter: @poshcodebear)
It is free for all to use, and free to distribute with attribution to the original author.
This is a special version modified specifically for the Scripting Games.
.PARAMETER ComputerName
The name of the Computer to check; if left blank, it defaults to "localhost".
Get-PCBUptime -ComputerName system
[string[]]$ComputerName = 'localhost'
foreach ($Computer in $ComputerName) {
if (Test-Connection -ComputerName $Computer -Quiet -Count 1) {
try {
# Query remote machine
$os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop
# Calculate start time and uptime (rounded to 1/10th of a day)
$StartTime = $os.ConvertToDateTime($os.LastBootUpTime)
$DaysUptime = [Math]::Round((((Get-Date) - $StartTime).TotalDays), 1)
$Status = 'OK'
# Determine if it might need to be patched
if ($DaysUptime -gt 30) { $PatchCheck = $true }
else { $PatchCheck = $false }
catch {
# There was a problem during the WMI query; set up different output and pass through the error
$StartTime = 'Unknown'
$DaysUptime = 0
$Status = 'ERROR'
$PatchCheck = $false
Write-Error $_
# Format output
$props = [ordered]@{
'ComputerName' = $Computer;
'StartTime' = $StartTime;
'Uptime(Days)' = $DaysUptime;
'Status' = $Status;
'MightNeedPatched' = $PatchCheck;
else {
# Ping failed; throw warning and format output accordingly
Write-Warning -Message "Computer $($Computer) does not respond to ping and may be offline"
$props = [ordered]@{
'ComputerName' = $Computer;
'StartTime' = $null;
'Uptime(Days)' = 0;
'Status' = 'OFFLINE';
'MightNeedPatched' = $false;
# Generate the output object with type
$obj = New-Object -TypeName PSObject -Property $props
Write-Output -InputObject $obj
END { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment