PowerShell LastBootUpTime WMI

How to Check Computer UpTime Using PowerShell 3.0

I have received a few surprises when using this WMI script to see when the computer last booted.  Some servers have clearly rebooted without me realizing (remembering!).  On the other hand, I have seen laptops which the script shows haven’t actually rebooted despite being turned off, hmm … must be hibernating.

 ♦

  

Simple PowerShell LastBootUpTime Script

Here we employ the versatile PowerShell cmdlet called GWMI (Get-WmiObject).  The particular class is Win32_OperatingSystem.

# Check Windows Uptime with PowerShell’s WMI
(Get-WmiObject Win32_OperatingSystem).LastBootUpTime

Note 1: From the dozens of Win32_OperatingSystem properties, all we need is the .LastBootUpTime and its value.

Date Format Problem
The problem with the above simple script is it’s hard to decipher the date. For example: 20120521170350.125599+060 
Solution: control the datetime format.
For example: 21 May 2012 17:03:50 (UK date format)

Decipher the Last Boot-up Time Result

Clear-Host
$Booted = (Get-WmiObject Win32_OperatingSystem).LastBootUpTime
[Management.ManagementDateTimeConverter]::ToDateTime($Booted)

Note 2: These examples are about understanding PowerShell WMI in general, and .LastBootUpTime in particular.  For a production script you could strip out Clear-Host, and generally write much tighter code.  See more on LastBootUpTime.

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

Download your free copy of WMI Monitor

Discover LastBootUpTime for Remote Computer

Here I have a few more ideas, firstly let us specify which computer to interrogate, and secondly, try a slightly easier way of handling the date format.

# Check Operating System Up Time with PowerShell
Clear-Host
$Computer = "LocalHost"
$Booted = Get-WmiObject -Class Win32_OperatingSystem -Computer $Computer
$Booted.ConvertToDateTime($Booted.LastBootUpTime)

Note 3: I forgot to substitute the Remote Computer’s name for "LocalHost"

Calculate Your Computer’s UpTime with PowerShell 3.0

Thanks to PowerShell’s [DateTime]::Now
we can make a simple subtraction to calculate how long the computer has been running.

# Calculate Windows server up-time with PowerShell
Clear-Host
$Computer = "LocalHost"
Write-Host "$Computer’s Uptime :"
$Booted = Get-WmiObject -Class Win32_OperatingSystem -Computer $Computer
[DateTime]::Now – $Booted.ConvertToDateTime($Booted.LastBootUpTime)`
| Format-Table Days, Hours -AutoSize

Note 4: The tiny backtick ` enables the Format-Table instruction to wrap onto the next line.  In PowerShell 2.0 a space before the backtick cause the script to fail, however, I haven’t found a space a problem in v 3.0.

These scripts for displaying a machine’s uptime were tested in PowerShell 3.0, however, they also work in version 2.0 and even 1.0.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Create PowerShell Function Called Get-UpTime

I regard creating functions as the pinnacle of a PowerShell beginner’s education.  If you can build your own functions then you have graduated to the intermediate scripting class.  At the core or 'Process' of this function is the WMI class Win32_OperatingSystem.

Function Global:Get-UpTime {
<#
.SYNOPSIS
PowerShell function to calculate computer uptime
.DESCRIPTION
Uses Win32_OperatingSystem to get LastBootUpTime for current computer
.EXAMPLE
Get-UpTime
#>
Param (
[String]$CompVictim = "LocalHost"
      ) # End of parameter section
Begin {
Clear-Host
        }
Process {
$Booted = Get-WmiObject -Class Win32_OperatingSystem -Computer $CompVictim
$Calc = [DateTime]::Now – $Booted.ConvertToDateTime($Booted.LastBootUpTime)
Write-Host "Computer Uptime for:" `
$CompVictim, $Calc.days "days and", $Calc.hours "hours"
     } # End of Process
}

Get-UpTime

Note 5: Think of the function as a {wrapper} inside those curly brackets.  This function only has one parameter, and I have set the default value to the local host.  To test just type: Get-UpTime.

Note 6: In this example the function’s name is Get-Uptime, I created it following the Verb-Noun pattern of built-in cmdlet functions.

See more on creating PowerShell functions »

Engineer's Toolset v10Guy Recommends: SolarWinds Engineer’s Toolset v10

This Engineer’s Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset now!

Download your fully functional trial copy of the Engineer’s Toolset v10

Back to PowerShell 3.0 Basics with Get-Member

Perhaps it’s just my ignorance, or poor memory, but whenever I call for Get-Member I discover an interesting property or method for the cmdlet I am experimenting with.  In this case it was .InstallDate.

# List Win32_OperatingSystem properties with PowerShell 3.0
Clear-Host
Get-WmiObject -Class Win32_OperatingSystem | Get-Member `
| Where-Object {$_.name -Notmatch "__" -And $_.MemberType -eq "Property"}

Challenge: I bet you find an even more interesting property than InstallDate.

If I am wrong, then try substituting "Method" for "Property".

Alternatives Strategies for Viewing a Computer’s UpTime

In this example we can use the little know Net Statistics command to see how long a computer has been running.

Net Statistics server | findstr /I "statistics since"

Note 7: Thanks to Paul DeBrino for alerting me to his technique.

Note 8: You can run the above command in PowerShell.  Indeed, one bonus of fixating on PowerShell is that you no longer need the old DOS box or cmd.exe Window, just run your those old commands such as ipconfig /all within PowerShell.

Summary of PowerShell v 3.0 Uptime

It is interesting to discover how long Windows computers have been up and running.  Take this opportunity to push your boundaries of PowerShell 3.0 knowledge.

If you like this page then please share it with your friends

 


See More PowerShell Function Parameters

Scripting PowerShell Function   • PowerShell Function Parameter  • Free Import User CSVDE Tool

PowerShell Function Get-ServiceStatus   • PowerShell Get-BrowseMaster   • PowerShell Send-Email

Create PowerShell Function   • PowerShell Function Get-WmiClass  • PowerShell Function Get-Uptime

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.