Monday, 22 December 2008

Get-ParsedString.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Formats a number using .NET - an MSDN Sample recoded in PowerShell 
  4. .DESCRIPTION 
  5.     This script createa a number and formats it in Hex. Then a negative number 
  6.     is created and formatted several ways. Uses int32.parse method to do the  
  7.     parsing. 
  8. .NOTES 
  9.     File Name  : Get-ParsedString 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell V2 CTP3 
  12. .LINK 
  13.     Posted to: 
  14.     http://pshscripts.blogspot.com/2008/12/get-parsedstringps1.html 
  15.     Script also posted to MSDN at: 
  16.     http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles(VS.85).aspx 
  17. .EXAMPLE 
  18.     PS c:\foo> .\Get-ParsedString.ps1 
  19.     A in hex = 10 in decimal 
  20.     '    -42    ' parsed to an int32 is '-42'
  21.     '    (42)   ' parsed to an int32 is '-42'
  22. #> 
  23.  
  24.  
  25. ### 
  26. #  Start of Script 
  27. ### 
  28.  
  29. # Parse the string as a hex value and display the value as a decimal. 
  30. $num = "A" 
  31. $val = [system.int32]::Parse($num, [System.Globalization.NumberStyles]::HexNumber) 
  32.  
  33. "{0} in hex = {1} in decimal" -f $num,$val 
  34.  
  35. # Parse the string, allowing a leading sign, and ignoring leading and trailing white spaces. 
  36. $num = "    -42    " 
  37.  
  38. # create parsing value using value__ 
  39. $format  = [System.Globalization.NumberStyles]::AllowLeadingSign.value__+ 
  40.            [System.Globalization.NumberStyles]::AllowLeadingWhite.value__ + 
  41.            [System.Globalization.NumberStyles]::AllowTrailingWhite.value__   
  42. $parsing = [System.Globalization.NumberStyles] $format      
  43.  
  44. # parse and display 
  45. $val = [system.int32]::Parse($num,$parsing
  46. "'{0}' parsed to an int32 is '{1}'." -f $num, $val 
  47.  
  48. # Now try a negative number 
  49. $num = "    (42)   " 
  50. $format  = [System.Globalization.NumberStyles]::AllowParentheses.value__  + 
  51.            [System.Globalization.NumberStyles]::AllowLeadingSign.value__  + 
  52.            [System.Globalization.NumberStyles]::AllowLeadingWhite.value__ + 
  53.            [System.Globalization.NumberStyles]::AllowTrailingWhite.value__ 
  54. $parsing = [System.Globalization.NumberStyles] $format              
  55.  
  56. # And parse/display it 
  57. $val = [system.int32]::Parse($num, $parsing
  58. "'{0}' parsed to an int32 is '{1}'." -f $num, $val 

No comments: