【问题标题】:Unexpected char when executing .ps1 file using PuTTY Plink使用 PuTTY Plink 执行 .ps1 文件时出现意外字符
【发布时间】:2018-09-17 21:22:55
【问题描述】:

我正在远程执行一些脚本,以使用 putty 中的 Plink 工具从服务器获取信息。当我使用 .ps1 文件时,问题就来了,因为一个“?”出现在开头,使第一行不正确,但使用 .bat 文件可以正常工作。

比如我要打印一个文件的内容:

GetDate.bat:

type C:/Data/DateOfCompilation.txt

然后:

PS C:/Users/MyUser> plink -ssh <User>@<IP> -i C:\Key.ppk -m C:\Scripts\GetDate.bat
10/09/2018 14:32:02,72

一切正常

GetDate.ps1:

Get-Content -Path C:/Data/DateOfCompilation.txt

执行:

PS C:/Users/MyUser> plink -ssh <User>@<IP> -i C:\Key.ppk -m C:\Scripts\GetDate.ps1

?Get-Content : The term '?Get-Content' 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 line:1 char:1 

+ ?Get-Content -Path C:/Data/DateOfCompilation.txt
+ ~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (?Get-Content:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

另外,如果我添加更多代码,其他行工作正常,它只是第一行失败,并在开头添加了 '?'

(但是,在本地运行脚本可以正常工作)

我还有其他更多的 ps1 脚本,所以只使用 bat 文件并不是最好的选择。

我查看了文档、其他论坛和此处,但我找不到任何东西。也许我对 ps1 文件一无所知。

【问题讨论】:

    标签: windows powershell ssh putty plink


    【解决方案1】:

    检查GetDate.ps1开头是否有UTF-8 BOM - 如果有,将其删除。


    尽管您的问题的根本原因可能是您对 Plink 的 -m 开关的误解。它使 Plink 读取文件并将其内容(并且仅是内容)发送到服务器。服务器永远不会知道文件扩展名是什么。所以使用 .ps 与 .bat 是没有意义的。无论扩展名是什么,该文件都将由您的 Windows SSH 服务器的默认 shell 解释。什么是 PowerShell(根据错误消息)。

    因此,即使是 .bat 文件中的 type 命令也是由 PowerShell 执行的,而不是由 cmd.exe 执行的。在 PowerShell 中,typeGet-Content 的别名。

    你的 .bat 文件工作的原因很可能是它没有 BOM,而你的 .ps1 有 BOM。如果您使用 PowerShell 执行了 .ps1,它将正确处理 BOM。但是您不是在使用 PowerShell 执行 .ps1,而是在执行其内容,在这种情况下,BOM 可能会导致问题。

    区别基本上是这样的:

    powershell.exe -File GetDate.ps1
    

    powershell.exe < GetDate.ps1
    

    两者的作用基本相同,但后者因 BOM 失败,而前者正确处理。

    【讨论】:

    • 如此真实!我检查了文件的十六进制代码并从 EF BB BF(你说的 BOM)开始。但是,使用记事本创建 ps1 没有 BOM 并且可以工作,可能 PowerShell ISE 在您创建文件时添加它。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-09-26
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 2021-02-06
    相关资源
    最近更新 更多