嗨,我有一个脚本来自动化一些任务,运行在powershell core v.7.+。
在其中一个脚本中,当我在ps1文件中运行命令时,返回的特殊字符被编码,我无法解码成正确的格式,下面是用来做这件事的命令和返回。
// 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"
*/
但是当我直接在终端运行同样的命令时,返回的字符串是:。
/*
* "nächste",
* "nächstgelegene"
*/
我想知道怎样才能在文件中运行命令而不对回车进行编码。我已经尝试了一些东西,如。
$encoding = [System.Text.Encoding]::Unicode
$model = pwsh -Command $script
Write-Output $model
$model = $encoding.GetBytes($model)
$model = $encoding.GetString($model)
但没有达到预期的效果,我不知道如何才能做到这一点,如果有人能帮助我,我非常感激。
尝试将字符串以字节形式返回,然后从你调用函数pwsh的地方进行解码。这将使它免受任何变化的影响。你所做的是在接收后将其转换为字节,然后将其返回为字符串。
下面是我的脚本。
(Get-Content "$currentPath\skill-package\skill.json" -Raw | ConvertFrom-Json).manifest.publishingInformation.locales.PSObject.Properties | ForEach-Object {
$lang = $_.Name
Write-Output "Profile: $profile skill-id: $skillId language: $lang"
$script = "ask smapi get-interaction-model -l $lang -s $skillId -p $profile -g $env"
Write-Output 'Running script'
Write-Warning $script
# $encoding = [System.Text.Encoding]::ASCII
$model = pwsh -Command $script
Write-Output $model
$model = $model
| ConvertFrom-Json -Depth 100
| Select-Object * -ExcludeProperty version
| ConvertTo-Json -Depth 100
# out-file "$file$lang.json" -InputObject $model -Encoding ascii
Write-Output "New model saved locally $file$lang.json"
}
Write-Warning 'Finished!!!'
(Get-Content "$currentPath\skill-package\skill.json" -Raw | ConvertFrom-Json).manifest.publishingInformation.locales.PSObject.Properties | ForEach-Object {
$lang = $_.Name
Write-Output "Profile: $profile skill-id: $skillId language: $lang"
$script = "`$command = ask smapi get-interaction-model -l $lang -s $skillId -p $profile -g $env;`$command = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes(Invoke-Expression `$command));`$command"
Write-Output 'Running script'
Write-Warning $script
# $encoding = [System.Text.Encoding]::ASCII
$model = pwsh -Command $script
$model = Text.Encoding::Unicode.GetString([Convert]::FromBase64String($model))
Write-Output $model
$model = $model
| ConvertFrom-Json -Depth 100
| Select-Object * -ExcludeProperty version
| ConvertTo-Json -Depth 100
# out-file "$file$lang.json" -InputObject $model -Encoding ascii
Write-Output "New model saved locally $file$lang.json"
}
Write-Warning 'Finished!!!'
经过多次研究,我找到了一个最简单的方法来解决我的问题,Powershell默认有一个不同的输出编码器,在这种情况下使用,我唯一需要做的就是改变它。
我使用了这个命令。
$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
我发现这个问题解释了它是如何工作的,这对我帮助很大,更多的问题请看这个。回答.