Public/Get-ComputerUptime.ps1
<#
.SYNOPSIS Get the uptime of a remote computer. .DESCRIPTION This function retrieves the uptime of a remote computer by querying its Last Boot Time. It checks if the computer is reachable and then calculates the uptime. .PARAMETER ComputerName Specifies the name of the remote computer whose uptime you want to retrieve. .EXAMPLE Get-ComputerUptime -ComputerName "RemoteComputer" Retrieves the uptime of the specified remote computer. .NOTES Requires administrative privileges on the remote computer and appropriate permissions to use PowerShell remoting. #> function Get-ComputerUptime { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string]$ComputerName ) process { if (Test-Connection -ComputerName $ComputerName -Count 2 -Quiet) { try { $OSInfo = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName $LastBootTime = $OSInfo.ConvertToDateTime($OSInfo.LastBootUpTime) $Uptime = New-TimeSpan -Start $LastBootTime -End (Get-Date) $Output = "{0} Uptime: {1} Days, {2} Hours, {3} Minutes, {4} Seconds" -f $ComputerName, $Uptime.Days, $Uptime.Hours, $Uptime.Minutes, $Uptime.Seconds Write-Output $Output } catch { Write-Error $_.Exception.Message } } else { Write-Output "The $ComputerName is unreachable. Please inform the relevant team." } } } |