Wednesday, October 30, 2013

Find amount of time since Windows started

Whether you need to find out the time since a computer was turned on for ticketing purposes, just out of curiosity or to show off how long your server has been online to a friend, you have come to the right place. Here is a PowerShell function to find out how many Days, Hours, and Minutes since the machine was started.

Copy the below code into a PowerShell window.
<#
.CREATED BY:
    Chris Davis
.MODIFIED BY:
    Matthew A. Kerfoot
.MODIFIED ON:
    10\30\2013
.Synopsis
   Outputs how long since the last reboot
.DESCRIPTION
    This function gathers information regarding when $ComputeName was last rebooted. `
.EXAMPLE
   Get-Uptime localhost | ConvertTo-Html | Out-File C:\
   Referance - http://pc-addicts.com/my-powershell-scripts/
#>

function Get-Uptime { [CmdletBinding()]

param ( [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
           [string]$ComputerName = "$env:COMPUTERNAME" )

Begin { $OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computername
        $diff = $OS.ConvertToDateTime($OS.LocalDateTime) - $OS.ConvertToDateTime($OS.LastBootUpTime) }

Process { foreach ( $_ in $ComputerName ){ 
                   @{ "ComputerName" = $Computername
                      "Days" = $diff.Days
                      "Hours" = $diff.Hours
                      "Minutes" = $diff.Minutes } } }

End { New-Object -TypeName PSObject -Property $properties | Format-Table -AutoSize }}

Once the above code is pasted into a PowerShell prompt hit enter a couple times and type, 'Get-Uptime'.
[www.matthewkerfoot.com]> Get-Uptime
Name                           Value
----                           -----
Hours                          5
Days                           0
ComputerName                   VT-MKERFOOT-W8
Minutes                        52

PS [www.matthewkerfoot.com]>