Pages

Friday, July 8, 2022

Get-Uptime from Local machine via Get-CimInstance

There are so many different ways by which we can get the uptime of a Server, I have tried replicating the Get-Uptime cmdlet which is available after PowerShell 6.0.

Here is a simple PowerShell script that can be used to get uptime of local machine of servers which have PowerShell version lower than 6.0.

Please try your hands on it and modify it as per your need to have it tweaked a little to get the same information from remote computers :).

# Use this script to get uptime of the Local Machine using Get-CIMInstance Commandlet #
# Load the script in memory by dot sourcing it like . .\ScriptName.ps1                #
# Use it with or without -verbose switch                                              #
<#
# PS C:\> . .\Data\Get-Uptime.ps1
# MyServer-2 :  7 Days: 3 Hours: 31 Minutes: 57 Seconds
# PS C:\> Get-UpTime
# MyServer-2 :  7 Days: 3 Hours: 32 Minutes: 2 Seconds
# PS C:\> Get-UpTime -Verbose
# MyServer-2
 
  Days              : 7
  Hours             : 3
  Minutes           : 32
  Seconds           : 6
  Milliseconds      : 286
  Ticks             : 6175262861422
  TotalDays         : 7.14729497849769
  TotalHours        : 171.535079483944
  TotalMinutes      : 10292.1047690367
  TotalSeconds      : 617526.2861422
  TotalMilliseconds : 617526286.1422
#>

Function Get-UpTime {
    param (
        [switch] $Verbose
    )
    $Current = (get-date)
    $BootTime = (Get-CimInstance win32_operatingsystem).lastbootuptime
    $Output = $Current - $BootTime

    if ($Verbose) {
        Write-Output ($env:COMPUTERNAME).ToLower(); $Output
    }
    else {
        Write-host -NoNewline ($env:COMPUTERNAME).ToLower()": " $Output.Days Days: $Output.Hours Hours: $Output.Minutes Minutes: $Output.Seconds Seconds
    }
}

Here is how to use it.

Good Luck :)