Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
January 2016 Scripting Games
<#
.Synopsis
Get the up time for a list of machines
.EXAMPLE
Get-Uptime
.EXAMPLE
Get-Uptime -ComputerName COMPUTER01,COMPUTER02,COMPUTER03
.EXAMPLE
Get-Uptime -ComputerName COMPUTER01,COMPUTER02,COMPUTER03 | Format-Table
#>
function Get-Uptime
{
[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
# Param1 help description
[Parameter(ValueFromPipelineByPropertyName=$true,
Position=0)]
$ComputerName=$env:COMPUTERNAME
)
Begin
{
}
Process
{
ForEach($computer in $ComputerName)
{
$cimOK = $true
If(Test-Connection -Quiet $computer -Count 1)
{
try
{
$os = Get-CIMInstance Win32_OperatingSystem -ComputerName $computer -ErrorAction Stop
}
Catch
{
$cimOK = $false
}
If($cimOK)
{
# We've retrieved the OS information from CIM so can calculate our other fields
$status = "OK"
$startTime = $os.LastBootUpTime
$uptime = [math]::Round(($os.LocalDateTime - $os.LastBootUpTime).TotalDays,1)
If($uptime -ge 30)
{
$mightNeedPatched = $true
}
Else
{
$mightNeedPatched = $false
}
}
Else
{
# There was a problem with CIM
$status = "ERROR"
$startTime = ""
$uptime = ""
}
}
Else
{
$status = "OFFLINE"
$startTime = ""
$uptime = ""
Write-Warning "$computer is OFFLINE"
}
$props = [ordered]@{'ComputerName'=$computer;
'StartTime'=$startTime;
'Uptime (Days)'=$uptime;
'Status'=$status;
'MightNeedPatched'=$mightNeedPatched;
}
$obj = New-Object -TypeName PSObject -Property $props
Write-Output $obj
}
}
End
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment