【问题标题】:Getting error while executing powershell script from powershell从powershell执行powershell脚本时出错
【发布时间】: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

代码说明:

  1. 将脚本的路径赋值给一个变量。
  2. 将编码后的字符串赋值给一个变量
  3. 解码字符串并复制到文件中。
  4. 执行 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

请看以下几点。

  1. 执行 powerscript (C:\AshishG\powershell\script12.ps1) 时出现错误。
  2. 字符串是编码格式,我可以对其进行解码,我看到,解码后的字符串也很好。
  3. 我观察到,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更改文件的编码

标签: powershell powershell-5.0


【解决方案1】:

错误来自您创建的.ps1 文件,很可能来自编码字符串。

"Write-host..." 前面有一个非打印字符,在创建 .ps1 文件后执行以下命令可以证明这一点:

PS C:\>>[int[]][Char[]]((gc $localScriptPath)[0])[0]
65279
PS C:\>

&#65279 是一个 Unicode 字符“零宽度无间断空间”(U+FEFF)。 PowerShell 用Write-HOst 修饰它以创建一个无法识别的命令。

【讨论】:

    猜你喜欢
    • 2019-08-15
    • 1970-01-01
    • 2020-09-16
    • 2014-07-23
    • 2016-09-13
    • 2011-07-02
    • 2014-01-06
    • 2011-07-16
    • 2012-04-28
    相关资源
    最近更新 更多