Exchange Server Share

… Information sharing on Exchange Server …

PowerShell : Uptime of Multiple Servers

If I ask you a question, how do you check uptime of servers? Your answer would be definitely, through uptime.exe utility.

But now in PowerShell world if you want to check the uptime then this is the right place.

  • To find the uptime we need to get the time when computer last (re)booted, we can get the last boot time through WMI class Win32_OperatingSystem but that gives us time in integer so we need to convert it into Date-Time format.

#This line gets the Win32_OperatingSystem of a computer and save it into $wmi variable.

$wmi=Get-WmiObject -class Win32_OperatingSystem -computer $server

#This line takes the LastBootupTime from Win32_OperatingSystem class, convert it into Date Time format and save it into $LBTime variable.

$LBTime=$wmi.ConvertToDateTime($wmi.Lastbootuptime)

image

  • Now our uptime is the difference between current time of your system and the LastBootupTime, so we take a help of TimeSpan Constructor from .Net Framework Class Library to find the duration/difference of these two.

#This line gives us the duration between current time and last boot up time

[TimeSpan]$uptime=New-TimeSpan $LBTime $(get-date)

image

  • Now get the Days, Hours, and Minutes & Seconds of this span and that is our uptime.

#This line writes the uptime.

Write-host $server “Uptime: ” $uptime.days “Days” $uptime.hours “Hours” $uptime.minutes “Minutes” $uptime.seconds “Seconds”

image

Uptime for Multiple Servers

This script takes list of servers from servers.txt file and gives the uptime of all servers.

=========Get-Uptime.ps1 Script Code=========

$Servers = Get-Content “Servers.txt”

foreach($Server in $Servers)

{

$wmi=Get-WmiObject -class Win32_OperatingSystem -computer $server

$LBTime=$wmi.ConvertToDateTime($wmi.Lastbootuptime)

[TimeSpan]$uptime=New-TimeSpan $LBTime $(get-date)

Write-host $server “Uptime: ” $uptime.days “Days” $uptime.hours “Hours” $uptime.minutes “Minutes” $uptime.seconds “Seconds”

}

=========Get-Uptime.ps1 Script Code=========

Here is the example, uptime of three servers in my test environment.

image

Written by Amit Tank

April 7, 2008 at 1:47 pm

2 Responses

Subscribe to comments with RSS.

  1. Thanks for sharing!!🙂

    ilias

    May 8, 2008 at 10:13 am

  2. Thanks for this! I was trying to get the timespan conversion right. This is the way I ended up doing it (I like the smaller output):

    $OS = get-wmiobject win32_operatingsystem
    $starttime = $OS.converttodatetime($OS.LastBootUpTime)
    New-TimeSpan (get-date $Starttime) | select Days, Hours, Minutes | Ft -auto

    Jason

    August 5, 2008 at 9:37 pm


Comments are closed.

%d bloggers like this: