Using-Culture -Culture culture -Script {scriptblock}
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]
Comments
- Anonymous
March 05, 2006
This is great. How do I get the arabic script in my command prompt? I'm using Consolas. - Anonymous
March 06, 2006
> How do I get the arabic script in my command prompt?
Alas, you get a new console.
The current console does not support this. In V2, we'll be working on GUI console which will have full UNICODE support. We've published all the APIs necessary for someone else to do this today.
Jeffrey Snover
Monad Architect - Anonymous
April 24, 2006
Jeff-
I was pretty pleased to attend your seminar on the SE forum. This new technology inspires me to get back to scripting as I have not done so for many years.
You two were awesome showing us Monad
Thx
Guillermo - Anonymous
August 24, 2007
PingBack from http://www.fredrikwall.net/2007/08/24/another-culture-and-excel/