Home > Back-end >  Translating PS script without psd1 file
Translating PS script without psd1 file

Time:12-03

I'm a casual code writer. I'm in the self-assigned thread to create a script to install a software only available as an exe file for Windows and customize a bit some defaults stored in an xml file. This is a step/step process for me, each one being through big reading on the net and many trials. Being ATM at 5% estimated of the travel an (other :-( ) idea hit my mind : making the job also for English speaking people in addition to French, and publish the script so that any other can easily add their own language strings for messages. I discovered the MS scripts internationalization way that uses DATA section(s), psd1 files and some related commands.

My goal is to supply a single ps1 file, dot. My latest idea, based on what I recently read, was to have all the strings in the ps1 file, then based on $PSUIlocale export/create a temporary .\LG-lg\SetupThisSoft.psd1 I could Import-LocalizedData... what I guess is stupid (why export when we have the strings within the file?).

Do you have any idea to reach the goal? I now have some (better?) idea, using an array of yet-translated-locales, e.g. $AvailLng = "fr-FR","en-EN" then having one DATA section for each $Item I could ForEach test against $PSUILocale, but I have no idea how to "point"/"enable" the good DATA section. "en-EN" would be the last $Item as a default/fallback when $PSUILocale doesn't match any previous $Item...

Thanks for ideas

CodePudding user response:

Store your Data sections in a hashtable and use the locale identifier (fr-FR, en-US etc.) as the key:

# Store messages for multiple languages in $localizedMessages
$localizedMessages = @{
    'en-US' = Data {
        ConvertFrom-StringData @'
        Error = an error occurred
        Success = something wonderful happened
'@
    }
    'fr-FR' = Data {
        ConvertFrom-StringData @'
        Error = une erreur est survenue
        Success = quelque chose de merveilleux est arrivé
'@
    }
}

$defaultLanguage = 'fr-FR'

# Assign the appropriate language version to the variable that holds the messages for later use
$Messages = if($localizedMessages.ContainsKey($PSUICulture)){
    $localizedMessages[$PSUICulture]
} else {
    # If we don't have localized messages for the current culture, we fall back to our default language
    $localizedMessages[$defaultLanguage]
}

# ...

# This will now throw a different error message based on the current UI culture
Write-Error $Messages['Error']
  • Related