PoshCode Logo PowerShell Code Repository

Use-Culture.ps1 by Lee Holmes 3 years ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2226"></script>download | new post

From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes

  1. #############################################################################
  2. ##
  3. ## Use-Culture
  4. ##
  5. ## From Windows PowerShell Cookbook (O'Reilly)
  6. ## by Lee Holmes (http://www.leeholmes.com/guide)
  7. ##
  8. #############################################################################
  9.  
  10. <#
  11.  
  12. .SYNOPSIS
  13.  
  14. Invoke a scriptblock under the given culture
  15.  
  16. .EXAMPLE
  17.  
  18. Use-Culture fr-FR { [DateTime]::Parse("25/12/2007") }
  19. mardi 25 decembre 2007 00:00:00
  20.  
  21. #>
  22.  
  23. param(
  24.     ## The culture in which to evaluate the given script block
  25.     [Parameter(Mandatory = $true)]
  26.     [System.Globalization.CultureInfo] $Culture,
  27.  
  28.     ## The code to invoke in the context of the given culture
  29.     [Parameter(Mandatory = $true)]
  30.     [ScriptBlock] $ScriptBlock
  31. )
  32.  
  33. Set-StrictMode -Version Latest
  34.  
  35. ## A helper function to set the current culture
  36. function Set-Culture([System.Globalization.CultureInfo] $culture)
  37. {
  38.     [System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture
  39.     [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
  40. }
  41.  
  42. ## Remember the original culture information
  43. $oldCulture = [System.Threading.Thread]::CurrentThread.CurrentUICulture
  44.  
  45. ## Restore the original culture information if
  46. ## the user's script encounters errors.
  47. trap { Set-Culture $oldCulture }
  48.  
  49. ## Set the current culture to the user's provided
  50. ## culture.
  51. Set-Culture $culture
  52.  
  53. ## Invoke the user's scriptblock
  54. & $ScriptBlock
  55.  
  56. ## Restore the original culture information.
  57. Set-Culture $oldCulture

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me