Get Uptime Using WMI and PowerShell

Grabbing a system’s uptime can be very useful information when troubleshooting.  This function will use WMI to calculate a system’s uptime.  It works on local and remote systems and you can specify credentials for the WMI call if you need to. It will return a System.TimeSpan value.

Here is an example:

2

Function Code:

Get-Uptime

function Get-Uptime {
<#
.SYNOPSIS
Get Uptime of Windows Computer
.DESCRIPTION
Get-Uptime will pull WMI uptime information from a Windows computer
.EXAMPLE
Get-Uptime

DESCRIPTION
-----------
This command will return the uptime for the local system
.EXAMPLE
Get-Uptime -computerName "SERVER1"

DESCRIPTION
-----------
This command will return the uptime for the system named SERVER1
#>
    [CmdletBinding()] param (
        [parameter(Mandatory=$false)] [string]$ComputerName=$env:COMPUTERNAME,
        [parameter(Mandatory=$false)] [Management.Automation.PSCredential] $Credential
    )
    PROCESS {
        
        #get wmi OS information
        try {
            if($Credential) {
                $wmic = gwmi Win32_OperatingSystem -computername $ComputerName -ErrorAction Stop -Credential $Credential
            }
            else {
                $wmic = gwmi Win32_OperatingSystem -computername $ComputerName -ErrorAction Stop    
            }
        }
        catch {
            Write-Host "`n$_`n" -ForegroundColor Magenta
            return
        }
        if ($wmic.lastbootuptime -eq $null) {
            Write-Host "`nWARNING: No Boot Time Data Found`n" -ForegroundColor Yellow
            return
        }
        
        #return timespan between now and last boot time
        return ( (Get-Date) - ($wmic.ConvertToDateTime($wmic.lastbootuptime)) )
        
    }
}

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>