Skip to main content

Program: Invoke a Script Block with Alternate Culture Settings

Given PowerShell’s diverse user community, scripts that you share will often be run on a system set to a language other than English. To ensure that your script runs properly in other languages, it is helpful to give it a test run in that culture. Example 126 lets you run the script block you provide in a culture of your choosing.

Example 126. UseCulture.ps1

############################################################################## ## ## UseCulture.ps1 ## ## Invoke a scriptblock under the given culture ## ## ie: ## ## PS >UseCulture frFR { [DateTime]::Parse("25/12/2007") } ## ## mardi 25 décembre 2007 00:00:00## ## ##############################################################################

Example 126. UseCulture.ps1 (continued)

param( [System.Globalization.CultureInfo] $culture = $(throw "Please specify a culture"), [ScriptBlock] $script = $(throw "Please specify a scriptblock") )

## A helper function to set the current culture function SetCulture([System.Globalization.CultureInfo] $culture) {

[System.Threading.Thread]:: CurrentThread.CurrentUICulture = $culture [System.Threading.Thread]:: CurrentThread.CurrentCulture = $culture }

## Remember the original culture information $oldCulture = [System.Threading.Thread]:: CurrentThread.CurrentUICulture

## Restore the original culture information if ## the user's script encounters errors. trap { SetCulture $oldCulture }

## Set the current culture to the user's provided ## culture. SetCulture $culture

## Invoke the user's scriptblock & $script

## Restore the original culture information. SetCulture $oldCulture

For businesses running Windows applications for international users, a Germany Dedicated Server provides dedicated infrastructure for PowerShell automation, locale testing, application configuration, and production workloads.

Help Category