Private/ADLookups/_GetUptime.ps1
function _GetUptime { <# .SYNOPSIS Outputs the last bootup time and uptime for one or more computers. .DESCRIPTION Outputs the last bootup time and uptime for one or more computers. .PARAMETER Computer One or more computer names. The default is the current computer. Wildcards are not supported. .OUTPUTS PSObjects containing the computer name, the last bootup time, and the uptime. #> [CmdletBinding()] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Blackholes are fun ways to nullify output.')] param( [Parameter(Mandatory = $true, ValueFromPipeline)] $Identity ) begin { $Object = @() $ErrorActionPreference = 'Stop' } process { foreach ($Computer in $Identity) { # Convert an ADComputer object to just the computer's name as string switch ($Computer.GetType().Name) { { ($_ -eq 'ADComputer') -or ($_ -eq 'PSCustomObject') } { Write-Verbose 'Provided input is a computer object, not a hostname string. Converting.' $Computer = $Computer.Name Write-Verbose "Converted to: $Computer" } Default { } } # Validate computer name try { $Blackhole = Get-ADComputer -Identity $Computer } catch { Write-Error "$Computer not found!" continue } If (-not (Test-Connection -ComputerName $Computer -Quiet -Count 1 -ErrorAction SilentlyContinue)) { Write-Warning "$Computer is Offline" $Object += [PSCustomObject]@{ 'Computer Name' = $Computer 'Last Boot Time' = 'Offline' Uptime = '0' } continue } $params = @{ 'ClassName' = 'Win32_OperatingSystem' 'ComputerName' = $Computer } try { $CimOS = Get-CimInstance @params } catch { Write-Warning "Cannot connect to the computer $Computer" continue } $Object += [PSCustomObject]@{ 'Computer Name' = $Computer 'Last Boot Time' = $CimOS.LastBootUpTime Uptime = (Get-Date) - $CimOS.LastBootUpTime | _FormatTimeSpan } } } end { $Object } } |