简体   繁体   中英

What is the best way to implement translation for a PowerShell script?

I am working on a PowerShell script that will need to be available in 2 languages. To make my life easier, it seems like a good idea to me to create a language file for each, and include the strings in there, rather than having the text directly in the code and maintaining 2 copies of the code. Is there a best practice on how to implement this?

The roadblock that I'm at right now is that some of the strings will need to contain variables, so I've already run into some trouble there. I've noticed that it will use the value of the variable at the time that the string is set, which makes sense to me.

So for example, if I have a string which outputs an error level:

$Strings.ErrorMessage = "Error detected with $Level severity"

And then later set $Level to to whatever value, it won't have that value when the script is called. Assuming that $Level isn't set before setting $Strings.ErrorMessage , The output would look like:

Error detected at  severity

Is there a way to tell PowerShell to grab the current value of the $Level variable before it is output?

When it comes to best practices, PowerShell's own help system has a page about that:

Get-Help about_Script_Internationalization

To avoid running into problems with expanding variables in localised strings, you can use the format string operator instead:

'Error detected with {0} severity' -f $Level

See this link on about_Script_Internationalization and this link that goes gives an example:

PSUICultureExample.ps1 before localistion

[System.Windows.Forms.MessageBox]::Show(
    "This is a small example showing how to localize strings in a PowerShell script.",
    "Hello, World!") | Out-Null

Code to create two localised scripts.

Localized\\PSUICultureExample.psd1

ConvertFrom-StringData @"
MessageTitle = Hello, World!
MessageBody = This is a small example showing how to localize strings in a PowerShell script.
OtherMessage = Hello {0}!
"@

Localized\\es-ES\\PSUICulture.psd1

ConvertFrom-StringData @"
MessageTitle = ¡Hola mundo!
MessageBody = Este es un pequeño ejemplo que muestra cómo localizar cadenas en un script de PowerShell.
OtherMessage = ¡Hola {0}!
"@

PSUICultureExample.ps1 AFTER localistion

$s = Import-LocalizedData -BaseDirectory (Join-Path -Path $PSScriptRoot -ChildPath Localized)
[System.Windows.Forms.MessageBox]::Show($s.MessageBody, $s.MessageTitle) | Out-Null

Then to include values within your strings (interpolation), you'd do something like this:

$ValueToInsert = 'Bob'
$s.OtherMessage -f $ValueToInsert

Edit Folders Localized & Localized\\es-ES are relative to the script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM