![](/img/trans.png)
[英]Why storage replica failover failed either use New-PSSession or Enter-PSSession
[英]Powershell New-PSSession and Enter-PSSession usage to copy file from source server to destination server
我在同時使用 New-PSSesion 和 Enter-PSSesion 時遇到錯誤,但它們是分開工作的。 我的目標是將文件從本地服務器復制到遠程服務器,然后在遠程服務器上運行一些命令
下面是我的腳本:
$Session = New-PSSession -ComputerName "IP_Address" -Credential "domainname\username"
Copy-Item "C:\Users\username\test1.txt" -Destination "C:\Users\username\" -ToSession $Session
Enter-PSSession $Session
Copy-Item "C:\Users\username\" -Destination "C:\Users\username\targetdir\"
...
Exit-PSSession
當我使用 PowerShellISE 運行上面的腳本時,它會導致錯誤:
Copy-Item : Cannot find path 'C:\Users\username\test1.txt' because it does not exist.
At line:4 char:1
+ Copy-Item "C:\Users\username\test1.txt" -Dest ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\username\test1.txt:String) [Copy-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
奇怪的是,當我從 powershell CLI(不是 ISE)運行它們時,它起作用了。
這背后的原因是什么?
Enter-PSSession
的目的是在用戶必須手動退出的遠程機器上輸入交互式session ,方法是提交exit
或其等效項(僅在遠程會話中), Exit-PSSession
[1]
在腳本中使用它的唯一可能原因是暫停正在運行的腳本,以便進入用戶可以在其中操作的交互式遠程 session 。 一旦用戶退出交互式 session,腳本將在本地繼續。
但是,由於一個錯誤從 PowerShell 7.2.1 開始實際上不起作用,並且執行意外地立即在本地繼續(這就是您所看到的) - 請參閱此答案。
對於自動遠程執行,請改用Invoke-Command
。
它要求您以腳本塊{... }
的形式將所有要遠程執行的語句傳遞給它的-ScriptBlock
參數。
如果您需要在不同時間將多批語句傳遞到遠程計算機,您可以使用New-PSSession
創建一個顯式 session object 並將它用於每個帶有-Session
參數的Invoke-Command
調用(而不是隱式創建一個 -通過-ComputerName
關閉 session)。
有關詳細信息,請參閱概念性的about_Remote幫助主題。
在您的情況下,將Enter-PSSession... Exit-PSSession
行塊替換為以下內容:
Invoke-Command -Session $Session -ScriptBlock {
Copy-Item "C:\Users\username\" -Destination "C:\Users\username\targetdir\"
# ...
}
[1] Exit-PSSession
存在主要是為了與Enter-PSSession
對稱。 沒有嚴格的理由使用它; 總是使用exit
- 它在本地和遠程會話中都有效 - 很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.