Wednesday 21 January 2009

Get-TryCatchFinally.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Shows Try/Catch/Finally using Powershell 
  4. .DESCRIPTION 
  5.     This is an MSDN Sample, re-written in PowerShell 
  6. .NOTES 
  7.     File Name  : get-trycatchfinally.ps1 
  8.     Author     : Thomas Lee - tfl@psp.co.uk 
  9.     Requires   : PowerShell V2 CTP3 
  10. .LINK 
  11.     Original script posted to: 
  12.     http://pshscripts.blogspot.com/2009/01/get-trycatchfinallyps1.html
  13.     MSDN Sample at: 
  14.     http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx 
  15. .EXAMPLE 
  16.     PS C:\foo> .\Get-TryCatchFinally.ps1 
  17.     Error in conversion 
  18.     Error record: Cannot convert value "Some string" to type "System.Int32". Error: "Input string was not in a correct format." 
  19.     $i = 123 
  20.     $i = System.Int32 
  21. #> 
  22.  
  23. ### 
  24. # Start of script 
  25. ### 
  26.  
  27. # Create some explicitly typed values 
  28. [int]    $i = 123 
  29. [string] $s = "Some string" 
  30. [object] $o = $s 
  31.  
  32. # Now try to convert an object into an integer (which will fail) 
  33.  
  34. try { 
  35. # Invalid conversion; $o contains a string not an int 
  36. $i = [int] $o 
  37.  
  38. # catch the error and display 
  39. catch { 
  40. "Error in conversion" 
  41. "Error record: {0}" -f $Error[0] 
  42. # Clean up 
  43. finally { 
  44. "`$i = {0}" -f $i 
  45. "`$i = {0}" -f $i.gettype() 
  46. # End of Script 

No comments: