【发布时间】:2021-12-31 05:07:00
【问题描述】:
执行以下代码时出现以下错误 代码:
$localScriptPath= "C:\AshishG\powershell\script12.ps1"
$ëncodedResonse = "77u/V3JpdGUtSG9zdCAnc2NyaXB0IGlzIGV4ZWN1dGVkIHN1Y2Nlc3NmdWxseScNCg0KcmV0dXJuICdUaGlzIGlzIHNjcmlwdCBvdXRwdXQn"
Write-Output "ëncodedResonse used is $ëncodedResonse"
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($ëncodedResonse)) | Out-File $localScriptPath -Force
$Content2 = get-content $localScriptPath
Write-Host "DECODED: " $Content2
$output =Invoke-Expression "& `"$localScriptPath`" "
Write-Host "scriptPath" used is $output
代码说明:
- 将脚本的路径赋值给一个变量。
- 将编码后的字符串赋值给一个变量
- 解码字符串并复制到文件中。
- 执行 PowerShell 脚本并出现错误。
错误:
Write-Host : The term 'Write-Host' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At C:\AshishG\powershell\script12.ps1:1 char:1
+ Write-Host 'script is executed successfully'
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Write-Host:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
请看以下几点。
- 执行 powerscript (C:\AshishG\powershell\script12.ps1) 时出现错误。
- 字符串是编码格式,我可以对其进行解码,我看到,解码后的字符串也很好。
- 我观察到,script12.ps1 是以 UTF-16 LE BOM 格式生成的。是不是造成了问题?
我写了完整的代码,因为我不确定问题是什么?
【问题讨论】:
-
在终端运行“Write-Host hello world”就可以了?
-
是的,我能做到。
-
我怀疑是您文件编码的问题。
-
在 PowerShell 版本 5.x 中,
Out-File的默认编码是 Unicode (Utf16-LE),但您期望的是 Utf8(有或没有 BOM)。这意味着脚本在文件内容开始的字节顺序标记(0xFF 0xFE)上阻塞。使用Set-Content或使用参数-Encoding更改文件的编码