List all cultures by extending the native Get-Culture cmdlet

I recently needed to list all possible cultures available on a Windows box.
I’ve looked for a native cmdlet that you’d do it by typing:

Get-command *culture*


After using the Get-Member cmdlet on the output of the Get-Culture cmdlet, I found a .Net way of achieving this by doing:

[System.Globalization.CultureInfo]::GetCultures(
[System.Globalization.CultureTypes]::AllCultures
)

It’s nice and I thought that it would be great to have a -All switch on the native Get-Culture cmdlet.
Lee Holmes from the Windows PowerShell Team at Microsoft recently demonstrated a mind-blowing way of extending cmdlets with a few lines of code on his blog.

After playing with what Lee Holmes presented and how that would apply for extending the native Get-Culture cmdlet, I came up with this:

$MetaData = New-Object System.Management.Automation.CommandMetaData (Get-Command Get-Culture -CommandType Cmdlet)
$functionContent = ([System.Management.Automation.ProxyCommand]::Create($MetaData))
$newcode = @'
if ($PSBoundParameters['All']) {
$scriptCmd = { & { [System.Globalization.CultureInfo]::GetCultures([System.Globalization.CultureTypes]::AllCultures) }}
} else {
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-Culture', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
}
'@
$line1 = "\`$wrappedCmd\s\=\s\`$ExecutionContext\.InvokeCommand\.GetCommand\('Get\-Culture\'\,\s\[System\.Management\.Automation\.CommandTypes\]::Cmdlet\)`r`n"
$line2 = "\s*\`$scriptCmd\s=\s\{&\s\`$wrappedCmd\s@PSBoundParameters\s}"
$updatedFunction = $functionContent -replace (($line1,$line2)-join,''),$newcode
$updatedFunction = $updatedFunction -replace 'param\(\)','param([switch]${All})'
Set-Item -Path function:\GLOBAL:Get-Culture -Value $updatedFunction -Force
view raw Get-Culture.ps1 hosted with ❤ by GitHub

I’ve tested the above code on PowerShell version 2.0. Guess what! It works 😎

To get a sorted list of cultures that match the following pattern “en-US” for example, you can do (on PowerShell version 3.0):

Get-Culture -All | 
? Name -match "^[a-z]{2}-[A-Z]{2}$"  | 
Sort Parent

1 thought on “List all cultures by extending the native Get-Culture cmdlet

  1. Pingback: Dew Drop – April 7, 2015 (#1988) | Morning Dew

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.