Tuesday, 13 January 2009

Get-UpTime.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Demonstrates uptime using WMI  
  4. .DESCRIPTION 
  5.     This script used Win32_ComputerSystem to determine how long your system 
  6.     has been running. This is a rewrite/improvement of sample 3 at 
  7.     http://msdn.microsoft.com/en-us/library/aa394591(VS.85).aspx.  
  8. .NOTES 
  9.     File Name : Get-UpTime.ps1 
  10.     Author : Thomas Lee - tfl@psp.co.uk 
  11.     Requires : PowerShell V2 CTP3 
  12. .LINK 
  13.     Script Posted to:  
  14.     http://www.pshscripts.blogspot.com 
  15.     Original sample posted at: 
  16.     http://msdn.microsoft.com/en-us/library/aa394591(VS.85).aspx 
  17. .EXAMPLE 
  18.     PS c:\foo> .\Get-UpTime.Ps1 
  19.     System Up for: 1 days, 8 hours, 40.781 minutes 
  20.  
  21. #> 
  22.  
  23. ## 
  24. #  Start of script 
  25. ## 
  26.  
  27. # Helper Function - convert WMI date to TimeDate object 
  28. function WMIDateStringToDate($Bootup) { 
  29.     [System.Management.ManagementDateTimeconverter]::ToDateTime($Bootup
  30.  
  31. # Main script 
  32. $Computer = "." # adjust as needed 
  33. $computers = Get-WMIObject -class Win32_OperatingSystem -computer $computer 
  34.  
  35. foreach ($system in $computers) { 
  36.     $Bootup = $system.LastBootUpTime 
  37.     $LastBootUpTime = WMIDateStringToDate($Bootup
  38.     $now = Get-Date 
  39.     $Uptime = $now - $lastBootUpTime 
  40.     $d = $Uptime.Days 
  41.     $h = $Uptime.Hours 
  42.     $m = $uptime.Minutes 
  43.     $ms= $uptime.Milliseconds 
  44.     "System Up for: {0} days, {1} hours, {2}.{3} minutes" -f $d,$h,$m,$ms 
  45. }  
  46. # End script 

0 comments: