Showing posts with label finally. Show all posts
Showing posts with label finally. Show all posts

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 

Sunday, 23 November 2008

Catch-Error.ps1

<#
.SYNOPSIS
    Demonstrates try/catch/finally in V2
.DESCRIPTION
    Shows a simple example of the try/catch/finally syntax
    introduced into PowerShell V2 CTP3 . The script divides by
    zero which creates an exception. The PowerShell parser
    is smart enough to recognise any attempt to divide 
    by "0" and therefore does not generate the run time error.
.NOTES
    File Name  : Show-TryCatchFinally.ps1
    Author     : Thomas Lee - tfl@psp.co.uk
    Requires   : PowerShell V2
.LINK
   http://pshscripts.blogspot.com/2008/11/catch-errorps1.html
#>

##
# Start of script
##

# Try something that fails
$one=1
$zero=0
Try
  { 
      $one/$zero
  }
Catch{
 'Caught in a catch block'
 $Error[0]
}
Finally {'All done with trying and catching'
}