Skip to content

Instantly share code, notes, and snippets.

@mwu17
Last active January 22, 2016 15:58
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 mwu17/d1a6765ddfc1d53de694 to your computer and use it in GitHub Desktop.
Save mwu17/d1a6765ddfc1d53de694 to your computer and use it in GitHub Desktop.
# Tested version: v5
<#
.Synopsis
Get Servers up time
.DESCRIPTION
2016-January Scripting Games Puzzle: Server uptime function
.EXAMPLE
PS C:\> Get-Uptime
ComputerName : DC1
StartTime : 1/15/2016 12:04:43 PM
Uptime(Days) : 6
Status : OK
MightNeedPatched : False
.EXAMPLE
PS C:\> Get-Uptime -computerName "DC1","W7-TEST" | Format-Table -AutoSize
ComputerName StartTime Uptime(Days) Status MightNeedPatched
------------ --------- ------------ ------ ----------------
DC1 1/15/2016 12:04:43 PM 6 OK False
W7-TEST 6 OFFLINE False
.EXAMPLE
PS C:\> $list = "DC1","W7-TEST"
PS C:\> $list | Get-Uptime | Format-Table -AutoSize
ComputerName StartTime Uptime(Days) Status MightNeedPatched
------------ --------- ------------ ------ ----------------
DC1 1/15/2016 12:04:43 PM 6 OK False
W7-TEST 6 OFFLINE False
#>
function Get-Uptime
{
[CmdletBinding()]
Param
(
# Computer name parameter
[Parameter(Position=0,
ValueFromPipeline,
ValueFromPipelineByPropertyName)
]
[ValidateNotNullorEmpty()]
[string[]]$computerName = $env:COMPUTERNAME
)
Begin
{
}
Process
{
foreach($computer in $computerName){
$LastBootTime = $null
$sysuptimeDays = $null
if(Test-Connection $computer -count 1 -Quiet){
try{
$wmi = Get-WmiObject -Class Win32_OperatingSystem -computername $computer -ErrorAction SilentlyContinue
$LastBootTime = $wmi.ConvertToDateTime($wmi.LastBootUpTime)
$sysuptime = (Get-Date) – $LastBootTime
$sysuptimeDays = $sysuptime.Days
$status = "OK"
# Check Might Need Patched property
if($sysuptime.days -ge 30){$mightNeedPatched = $true}
else{$mightNeedPatched = $false}
}
catch{
$status = "ERROR"
}
}
else{
$status = "OFFLINE"
}
# Save data in the object
$obj = [pscustomobject][ordered]@{
ComputerName = $computer
StartTime = $LastBootTime
'Uptime(Days)' = $sysuptime.Days
Status = $status
MightNeedPatched = $mightNeedPatched
}
$obj
}
}
End
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment