FRIHOSTFORUMSSEARCHFAQTOSBLOGSCOMPETITIONS
You are invited to Log in or Register a free Frihost Account!

Powershell - Getting computer uptime




This function will fetch the uptime of one or more computers.
sometimes it helps to know how long ago a remote computer was last rebooted.

Code:
<#
.Synopsis
   Get computer uptime info
.DESCRIPTION
   Get uptime info from the local or remote computers
.EXAMPLE   
   Get-ComputerUptime
   Get the uptime of the local computer
.EXAMPLE
   Get-ComputerUptime -ComputerName 'Lab01'
   Gets the uptime of a computer named Lab01
.EXAMPLE
   Get-ComputerUptime -ComputerName 'Lab01', 'Lab02'
   Gets the uptime of a computer named Lab01 and Lab02
.NOTES
   author: Marcuzzo
#>
function Get-ComputerUptime {

    [CmdLetBinding()]
    param(
        [Parameter( Mandatory = $false )]
        [string[]] $ComputerName = $env:COMPUTERNAME
    )

    Begin{
    }

    Process{
   
        foreach ( $Computer in $ComputerName) {
   
            if ( Test-Connection -ComputerName $Computer -Count 1 ){

                $vInstance = Get-CimInstance -ComputerName $Computer -ClassName Win32_OperatingSystem -Namespace 'Root\CIMV2' -Property LastBootUpTime
                   
                [System.DateTime] $LastBootUpDateTime = $vInstance.LastBootUpTime

                [System.TimeSpan] $timeSpan = [System.DateTime]::Now.Subtract($LastBootUpDateTime)

                [string] $uptime = [string]::Format("{0}d {1}h {2}m {3}s", $timeSpan.Days, $timeSpan.Hours, $timeSpan.Minutes, $timeSpan.Seconds);

                $UptimeInfo = @{
                'ComputerName' = $Computer;
                'LastBootUpTime' = $LastBootUpDateTime;
                'uptime' = $uptime
                }

                Write-Output (New-Object –Typename PSObject –Prop $UptimeInfo)

            }
            else{           
                Write-Error -Message ('The computer: "{0}" is OFFLINE!' -f $Computer)
            }
       
         }

    }
}




2 blog comments below

This is an AWESOME contribution Marcuzzo. Have you got something similar for servers? Cool
deanhills on Thu Oct 13, 2016 9:04 pm
This will/should work on any windows server.

I've used this to check the uptime of 2008 and 2012 ( both standard and R2 )

note: I use this on enterprise networks so you should definitely be on the same network
Marcuzzo on Thu Oct 13, 2016 11:22 pm



FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.