使用PuTTY Plink执行.ps1文件时出现意外的char

问题描述 投票:1回答:1

我正在使用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个回答
0
投票

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


虽然根本原因你的问题可能是你误解了Plink的-m开关。它使Plink读取文件并将其内容(仅内容)发送到服务器。服务器永远不会知道文件扩展名是什么。所以使用.ps vs .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,而第一个正确处理它。

© www.soinside.com 2019 - 2024. All rights reserved.