Last active
January 4, 2016 06:45
-
-
Save brianbunke/2c4fb81ed24cfb9610c2 to your computer and use it in GitHub Desktop.
PSGames-201601
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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