One of the traditional challenges with scripting is dealing with different CULTURES. Imagine the case where you are writing a script and you’ll have to parse datetime string from different cultures. If it was just one culture, you could set the process culture and be done with it. Here is a function that allows you to run a portion of a script in a different culture:
Function Using-Culture (
[System.Globalization.CultureInfo]$culture = (throw “USAGE: Using-Culture -Culture culture -Script {scriptblock}”),
[ScriptBlock]$script= (throw “USAGE: Using-Culture -Culture culture -Script {scriptblock}”))
{
$OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
trap
{
[System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
}
[System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
Invoke-Command $script
[System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
}
Here is an example of it working:
[332:]MSH> using-culture ar-IQ {get-date}
30 تشرين الثاني, 2005 09:01:38 ص
[332:]MSH> using-culture ar-IQ {$global:d=[DateTIme]::Parse(“30 تشرين الثاني, 2005 09:01:38 ص”)}
[332:]MSH> $d
Wednesday, November 30, 2005 9:01:38 AM
[332:]MSH> using-culture de-de {get-date}
Mittwoch, 30. November 2005 09:02:29
[332:]MSH> using-culture de-de {$global:d=[DateTIme]::Parse(“Mittwoch, 30. November 2005 09:02:29”)}
[332:]MSH> $d
Wednesday, November 30, 2005 9:02:29 AM
The great thing about this approach is that you can put any code you want into the script block. It can be a single cmd, a pipeline or a full script.
Enjoy!
Jeffrey P. Snover [MSFT]
[Edit: Monad has now been renamed to Windows PowerShell. This script or discussion may require slight adjustments before it applies directly to newer builds.]
0 comments