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 

4 comments:

Robert Meier said...

Bad numeric constant: 28..
At C:\users\rob.meier\Documents\Get-UpTime.ps1:28 char:4
+ 28. <<<< function WMIDateStringToDate($Bootup) {
+ CategoryInfo : ParserError: (28.:String) [], ParseException
+ FullyQualifiedErrorId : BadNumericConstant

Thomas said...

I just checked the script and it works perfectly here.

You may have cut/pasted incorrectly. It looks like when you did the cut/paste, you may have accidentally included the line numbers.

Robert Meier said...

Thank you. I found the mistake. The numbers for each line needed to be deleted.

Pat said...

Thomas-
I have about zero scripting experience, so you may not want to respond to my question, but how can I adapt this script to run against a list of computers in a single domain? I can create a text file with the computer names no problem. I am familiar with the concept of variables but not in the context of scripting.