Sunday 25 January 2009

Show-TryCatchFinally2.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     MSDN Sample of Try/Catch/Finally in PowerShell 
  4. .DESCRIPTION 
  5.     This script opens a file gets 1st 10 characters. The idea 
  6.     is to show more detail on try/catch/finally with PowerShell 
  7. .NOTES 
  8.     File Name  : show-trycatchfinally2.ps1 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell V2 CTP3 
  11.                  Also needs c:\foo\gd.txt to exist. 
  12. .LINK 
  13.     Script posted at:
  14.     http://pshscripts.blogspot.com/2009/01/show-trycatchfinally2ps1.html
  15.     MSDN Sample
  16.     http://msdn.microsoft.com/en-us/library/dszsf989.aspx
  17. .EXAMPLE 
  18.     PSH [C:\foo]: .Show-TryCatchFinally2.PS1' 
  19.     First 10 characters: 
  20.     N 
  21.     a 
  22.     m 
  23.     e 
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.     -  
  31.     - 
  32.     - 
  33. #> 
  34.  
  35. ### 
  36. # Start of Script 
  37. ## 
  38.  
  39. # Setup and open a file 
  40. $path = "c:\foo\gd.txt" 
  41. $file = new-object System.IO.StreamReader $path 
  42. $buffer = new-object char[] 10 
  43.  
  44. # now try and read the file 
  45. try { 
  46.   [void] $file.ReadBlock($buffer, $index, $buffer.Length) 
  47.   "First {0} characters:" -f $buffer.length 
  48.   $buffer 
  49. # catch IO exceptions 
  50. catch [System.IO.IOException] { 
  51. "Error reading from {0}. Message = {1}" -f $path, $Error[0].Message 
  52. #cleanup 
  53. finally { 
  54.  if ($file) { 
  55.   $file.Close() 

No comments: