PowerShell – Uptime of Multiple Machines – Example for Custom Formatting and Grid View

This post is to help you out in finding UpTime of one or more computers also you can pass file as its input parameter . Most of the time, the Powershell console might not fit all the required output columns. By default, the ordering of the columns are based on the width of an output data. The best way is to manage it through Custom Formatting or Grid View. This example will show an output in all three formats.

Download the code here Uptime

Function Get-Uptime
<#
.SYNOPSIS
Get uptime of a any given server
.DESCRIPTION
This function uses Win32_OperatingSystem WMI class to connect to remote machine and get lastboottime
.PARAMETER COMPUTERNAMES
Pass computer name as parameter
.EXAMPLE 1
Get-Uptime
.EXAMPLE 2
Get-Uptime -ComputerName Computername1,computername2
.EXAMPLE 3
Get-Uptime -ComputerName Computername1
.EXAMPLE
Get-Uptime -ComputerName (cat C:\PowerSQL\WinServers.txt)
.NOTES
To get help:
Get-Help Get-Uptime
.LINK

http://sqlpowershell.wordpress.com

#>
{
param
(
[Parameter(Position=0,Mandatory=$true)]
[alias(“cn”)]
[string[]]$ComputerName =”LocalComputer”
)

$Object =@()
foreach ($Computer in $ComputerName)
{
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$Uptime = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
$LastBootUpTime = $Uptime.ConvertToDateTime($Uptime.LastBootUpTime)
$Time = (Get-Date) – $LastBootUpTime
$Object += New-Object PSObject -Property @{
ComputerName = $Computer.ToUpper();
Uptime = ‘{0:00} Days, {1:00} Hours, {2:00} Minutes, {3:00} Seconds’ -f $Time.Days, $Time.Hours, $Time.Minutes, $Time.Seconds;}
}

}

$column1 = @{expression=”ComputerName”; width=15; label=”ComputerName”; alignment=”left”}
$column2 = @{expression=”Uptime”; width=45; label=”Uptime”; alignment=”left”}

# with Customized formatting
$Object|format-table $column1, $column2

#Without formatting
$Object|Format-Table -AutoSize

#Grid output
$Object.GetEnumerator() | Out-GridView -Title ” UpTime Details”

}

Output-

uptime

About these ads

About Prashanth Jayaram

I’m a Database technologist having 8+ years of rich, hands-on experience on Database technologies. I am Microsoft Certified Professional and backed with a Degree in Master of Computer Application. My expertise lies in T-SQL programming, Replication and PowerShell. hobbies are playing sports and drawing.
This entry was posted in PowerShell and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s