Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Powershell Use-Culture function

Provided by a coworker, who got it from somewhere on the Internet that I cannot source correctly:

function Use-Culture
{
   param(
      [Parameter(Mandatory)][CultureInfo]$Culture,
      [Parameter(Mandatory)][ScriptBlock]$ScriptBlock
   )
   # Note: In Windows 10, a culture-info object can be created from *any* string.
   #        However, an identifier that does't refer to a *predefined* culture is
   #        reflected in .LCID containing 4096 (0x1000)
   if ($Culture.LCID -eq 4096) { Throw "Unrecognized culture: $($Culture.DisplayName)" }
   # Save the current culture / UI culture values.
   $PrevCultures = [Threading.Thread]::CurrentThread.CurrentCulture, [Threading.Thread]::CurrentThread.CurrentUICulture
   try {
      # (Temporarily) set the culture and UI culture for the current thread.
      [Threading.Thread]::CurrentThread.CurrentCulture = [Threading.Thread]::CurrentThread.CurrentUICulture = $Culture
      # Now invoke the given code.
   & $ScriptBlock
   }
   finally {
      # Restore the previous culture / UI culture values.
      [Threading.Thread]::CurrentThread.CurrentCulture = $PrevCultures[0]
      [Threading.Thread]::CurrentThread.CurrentUICulture = $PrevCultures[1]
   }
}

You would use it in something like this:

Use-Culture -Culture en-US -ScriptBlock { Get-AdUserPasswordExpiration -Identity bgstack15 }

This might have been adapted from Windows PowerShell 2.0 String Localization | Keith Hill's Blog

Comments