How-to: Get the system uptime [Get-Uptime.ps1]

Get the system uptime for one or more computers.

For instructions of how to download and run this script see: Run a PowerShell script.

# Accept input from the pipeline
Param([Parameter(mandatory=$true,ValueFromPipeline=$true)] [string[]]$ComputerName = @("."))

# Process the piped input (one computer at a time)
process { 

   # See if it responds to a ping, otherwise the CIM queries will fail
   $ping = Test-connection "$ComputerName" -quiet
   if ($ping) {
      # Ping responded, so connect to the computer via CIM
      $os = Get-ciminstance Win32_OperatingSystem -ComputerName $ComputerName -ev myError -ea SilentlyContinue 

      if ($myError -ne $null) {
         # Error: CIM did not respond
         "$ComputerName did not respond"
      } else { 
         $LastBootUpTime = $os.ConvertToDateTime($os.LastBootUpTime)
         $LocalDateTime = $os.ConvertToDateTime($os.LocalDateTime)
   
         # Calculate uptime - this is automatically a timespan
         $up = $LocalDateTime - $LastBootUpTime

         # Split into Days/Hours/Mins
         $uptime = "$($up.Days) days, $($up.Hours)h, $($up.Minutes)mins" 

         # Save the results for this computer in an object
         $results = new-object psobject
         $results | Add-Member noteproperty LastBootUpTime $LastBootUpTime
         $results | Add-Member noteproperty ComputerName $os.csname
         $results | Add-Member noteproperty uptime $uptime

         # Display the results
         $results | Select-Object ComputerName,LastBootUpTime, uptime
      }

   # Next Ping result
   }

# End of the process block
}

Examples

Assuming the script above is saved in the current directory as get-uptime.ps1 :

PS C:\> ./get-uptime "server64","server65","server66" -AsPSObject

PS C:\> $servers = cat servers.txt |sort
PS C:\> $servers |./get-uptime -AsPSObject

This script is based on an original by Alex K. Angelopoulos

“Time and tide wait for no man” ~ Geoffrey Chaucer.

Related PowerShell Cmdlets

psinfo - List information about a system.
pshinfo - Get information about a machine - Ram, Disk Space, Service pack, Uptime.


 
Copyright © 1999-2024 SS64.com
Some rights reserved