Sunday, 19 June 2011

Get-ParsedInteger.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script parses several strings into integers, where possible.  
  4. .DESCRIPTION 
  5.     This script uses the TryParse method on [Int32] to attempt 
  6.     to parse a string into a number and writes the results. This script 
  7.     is a recoded MSDN sample using PowerShell 
  8. .NOTES 
  9.     File Name  : Get-ParsedInt32.ps1 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell Version 2.0 
  12. .LINK 
  13.     This script posted to: 
  14.         http://www.pshscripts.blogspot.com 
  15.     MSDN sample posted tot: 
  16.         http://msdn.microsoft.com/en-us/library/f02979c7.aspx 
  17. .EXAMPLE 
  18.     Psh[C:\foo]> .\get-parsedinteger.ps1 
  19. Attempted conversion of '' failed. 
  20. Converted '160519' to 160519. 
  21. Attempted conversion of '9432.0' failed. 
  22. Attempted conversion of '16,667' failed. 
  23. Converted '   -322   ' to -322. 
  24. Converted '+4302' to 4302. 
  25. Attempted conversion of '(100);' failed. 
  26. Attempted conversion of '01FA' failed.     
  27. #> 
  28.  
  29. # Define function to parse a string to integer 
  30. Function TryToParse { 
  31. # Parameter to parse into a number 
  32. Param ([string] $value
  33. # Define $number and try the parse 
  34. [int] $number = 0 
  35. $result = [System.Int32]::TryParse($value, [ref] $number); 
  36. if ($result)  { 
  37.       "Converted '{0}' to {1}." -f $value, $number  
  38.               } 
  39.       else    { 
  40.         if ($value -eq $null) {$value = ""}  
  41.        "Attempted conversion of '{0}' failed." -f $value 
  42.               } 
  43.  
  44. # Now call the function to see if the string will parse 
  45. TryToParse($null
  46. TryToParse("160519"); 
  47. TryToParse("9432.0"); 
  48. TryToParse("16,667"); 
  49. TryToParse("   -322   "); 
  50. TryToParse("+4302"); 
  51. TryToParse("(100);"); 
  52. TryToParse("01FA"); 
Technorati Tags: ,