Search code examples
powershellcharacter-encodingspecial-characterspowershell-core

Special characters is encoded when run script inside a file Powershell


Hi I have a script to automate some tasks, running in powershell core v.7.+.

In one of these scripts when I run the command inside the ps1 file and the special characters returned is encoded and I can't decode to right format, below the command used to do this and the return:

// the variable $script is my command its a ask-cli command to work in alexa
$model = pwsh -Command $script
/* 
* when I running the script from here the special characters returned is these:
* "nächste",
* "nächstgelegene"
*/

But when I run the same command directly in the terminal the strings returned are:

/*
* "nächste",
* "nächstgelegene"
*/

I would like to know how can I run the command inside the file without encode the return. I already tried some things as:

   $encoding = [System.Text.Encoding]::Unicode

    $model = pwsh -Command $script

    Write-Output $model

    $model = $encoding.GetBytes($model)

    $model = $encoding.GetString($model)

But don't work as expected, I don't know more how I can to this, if someone could help me with this I appreciate too much.


Solution

  • After many researches, I could find something more easiest to solve my problem. Powershell has by default a different output encoder used in these cases, and the only thing I need to do it's change it.

    I used the command:

    $OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
    

    I find this question explaining how this work and this help a lot, for more question please check this answer.