Skip to content

Instantly share code, notes, and snippets.

@brianbunke
Last active January 4, 2016 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianbunke/2c4fb81ed24cfb9610c2 to your computer and use it in GitHub Desktop.
Save brianbunke/2c4fb81ed24cfb9610c2 to your computer and use it in GitHub Desktop.
PSGames-201601
function Get-Uptime {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string[]]$ComputerName = $env:COMPUTERNAME
)
BEGIN {
# Define $Results array to append each computer into; get the current date once
$Results = @()
$Now = Get-Date
}
PROCESS {
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
}
}
}
END {
Write-Output $Results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment