Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
function Get-Uptime {
param (
[Parameter(ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string[]]$ComputerName = $env:COMPUTERNAME
# Define $Results array to append each computer into; get the current date once
$Results = @()
$Now = Get-Date
ForEach ($Computer in $ComputerName) {
# Reset $WMISuccess to default true for each new $Computer
$WMISuccess = $true
Write-Verbose "Testing connection to $Computer"
If (Test-Connection -ComputerName $Computer -Quiet -Count 1) {
# Try to query the computer via WMI for info
Write-Verbose "Retrieving WMI info from $Computer"
Try {$WMIOS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop}
Catch {$WMISuccess = $false}
# If WMI query was successful:
If ($WMISuccess -eq $true) {
# Take LastBootUpTime, use WMI's built-in convert to Posh DateTime object,
# and then use the .NET method to convert to sortable ('s') ISO 8601 format
$StartTime = ($WMIOS.ConvertToDateTime($WMIOS.LastBootUpTime)).GetDateTimeFormats('s')
# Subtract the boot time from now to get the running uptime
$Uptime = $Now - ($WMIOS.ConvertToDateTime($WMIOS.LastBootUpTime))
# Select the TotalDays property and round it to one decimal place
$UptimeDays = '{0:N1}' -f $Uptime.TotalDays
# Set $MightNeedPatched according to $UptimeDays result
If ($UptimeDays -ge 30) {$MightNeedPatched = $true}
Else {$MightNeedPatched = $false}
# Create an ordered hashtable of values
$Properties = [ordered]@{'ComputerName' = "$Computer"
'StartTime' = "$StartTime"
'Uptime (Days)' = [decimal]$UptimeDays
'Status' = 'OK'
'MightNeedPatched' = $MightNeedPatched
} Else {
# Create an ordered hashtable to note our WMI error
$Properties = [ordered]@{'ComputerName' = "$Computer"
'Status' = 'ERROR'
# Append the $Properties hashtable into $Results as an additional object
$Results += New-Object -TypeName PSObject -Property $Properties
} Else {
# No response from Test-Connection; mark as offline
# Create new object w/ hashtable as above
$Properties = [ordered]@{'ComputerName' = "$Computer"
'Status' = 'OFFLINE'
$Results += New-Object -TypeName PSObject -Property $Properties
Write-Output $Results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.