Skip to content

Instantly share code, notes, and snippets.

@poshcodebear
Created January 14, 2016 04:49
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 poshcodebear/19244b0751c4a24bbe78 to your computer and use it in GitHub Desktop.
Save poshcodebear/19244b0751c4a24bbe78 to your computer and use it in GitHub Desktop.
Scripting Games January 2016: Get-PCBUptime
function Get-PCBUptime {
<#
.SYNOPSIS
A simple tool for checking how long a system on the network has been running since last boot.
.DESCRIPTION
Get-PCBUptime is a quick WMI-based tool for determinging a remote system's uptime. It is useful for verifying
what a user says when asked if they've rebooted their machine recently, or to generate a report of server uptimes.
Get-PCBUptime is written by and copyright of Christopher R. Lowery, aka The PowerShell Bear (poshcodebear.com; Twitter: @poshcodebear)
It is free for all to use, and free to distribute with attribution to the original author.
This is a special version modified specifically for the Scripting Games.
.PARAMETER ComputerName
The name of the Computer to check; if left blank, it defaults to "localhost".
.EXAMPLE
Get-PCBUptime -ComputerName system
.LINK
http://www.poshcodebear.com
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias('Host')]
[string[]]$ComputerName = 'localhost'
)
BEGIN { }
PROCESS {
foreach ($Computer in $ComputerName) {
if (Test-Connection -ComputerName $Computer -Quiet -Count 1) {
try {
# Query remote machine
$os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop
# Calculate start time and uptime (rounded to 1/10th of a day)
$StartTime = $os.ConvertToDateTime($os.LastBootUpTime)
$DaysUptime = [Math]::Round((((Get-Date) - $StartTime).TotalDays), 1)
$Status = 'OK'
# Determine if it might need to be patched
if ($DaysUptime -gt 30) { $PatchCheck = $true }
else { $PatchCheck = $false }
}
catch {
# There was a problem during the WMI query; set up different output and pass through the error
$StartTime = 'Unknown'
$DaysUptime = 0
$Status = 'ERROR'
$PatchCheck = $false
Write-Error $_
}
# Format output
$props = [ordered]@{
'ComputerName' = $Computer;
'StartTime' = $StartTime;
'Uptime(Days)' = $DaysUptime;
'Status' = $Status;
'MightNeedPatched' = $PatchCheck;
}
}
else {
# Ping failed; throw warning and format output accordingly
Write-Warning -Message "Computer $($Computer) does not respond to ping and may be offline"
$props = [ordered]@{
'ComputerName' = $Computer;
'StartTime' = $null;
'Uptime(Days)' = 0;
'Status' = 'OFFLINE';
'MightNeedPatched' = $false;
}
}
# Generate the output object with type
$obj = New-Object -TypeName PSObject -Property $props
$obj.PSObject.TypeNames.Insert(0,'PoshCodeBear.System.UpTime')
Write-Output -InputObject $obj
}
}
END { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment