簡體   English   中英

使用PuTTY Plink執行.ps1文件時出現意外的char

[英]Unexpected char when executing .ps1 file using PuTTY Plink

我正在使用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文件一無所知。

檢查GetDate.ps1開頭是否有UTF-8 GetDate.ps1如果有,請將其刪除。


盡管造成問題的根本原因可能是您對Plink的-m開關有誤解。 它使Plink讀取文件並將其內容(和僅內容)發送到服務器。 服務器從不學習文件擴展名是什么。 因此,使用.ps vs .bat毫無意義。 不管擴展名是什么,該文件都將由Windows SSH服務器的默認外殼程序解釋。 什么是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,而第一個可以正確處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM