Friday 17 September 2010

Get-ArrayList2.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script demonstrates using an ArrayList 
  4. .DESCRIPTION 
  5.     This script re-implements an MSDN Sample using  
  6.     a System.Collection.ArrayList 
  7. .NOTES 
  8.     File Name  : Get-Arraylist2.ps1 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell Version 2.0 
  11. .LINK 
  12.     This script posted to: 
  13.         http://www.pshscripts.blogspot.com 
  14.     MSDN sample posted tot: 
  15.         http://msdn.microsoft.com/en-us/library/system.collections.arraylist.insert.aspx 
  16. .EXAMPLE 
  17.     Left as an exercise for the reader! 
  18.      
  19. #> 
  20. $myAL = New-Object system.Collections.ArrayList 
  21. $myAL.Insert( 0, "The"
  22. $myAL.Insert( 1, "fox"
  23. $myAL.Insert( 2, "jumps"
  24. $myAL.Insert( 3, "over"
  25. $myAL.Insert( 4, "the"
  26. $myAL.Insert( 5, "dog"
  27.  
  28. # Create and initializes a new Queue. 
  29. $myQueue = New-Object system.Collections.Queue 
  30. $myQueue.Enqueue( "quick"
  31. $myQueue.Enqueue( "brown"
  32.  
  33. # Displays the ArrayList and the Queue. 
  34. "The ArrayList initially contains the following:" 
  35. $myAL 
  36. "The Queue initially contains the following:" 
  37. $myQueue 
  38.  
  39. # Copy the Queue elements to the ArrayList at index 1. 
  40. $myAL.InsertRange( 1, $myQueue
  41.  
  42. # Displays the ArrayList. 
  43.  "After adding the Queue, the ArrayList now contains:"  
  44.  $myAL 
  45.   
  46.  # Search for "dog" and add "lazy" before it. 
  47.  $myAL.Insert( $myAL.IndexOf( "dog" ), "lazy"
  48.  
  49. # Display the ArrayList. 
  50. "After adding `"lazy`", the ArrayList now contains:"  
  51. $myAL 
  52.  
  53. # Add "!!!" at the end. 
  54.  $myAL.Insert( $myAL.Count, "!!!"
  55.   
  56. # Display the ArrayList. 
  57. "After adding `"!!!`", the ArrayList now contains:" 
  58. $myAL 
  59.  
  60. # Inserting an element beyond Count throws an exception. 
  61. try  { 
  62.      $myAL.Insert( $myAL.Count+1, "anystring"
  63.       }  
  64. catch { 
  65. "Exception: " + $Error[0] 
  66.       } 

No comments: