Powershell New-PSSession 和 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's purpose is to enter an interactive session on a remote machine that the user must exit manually, by submitting exit or its equivalent (in remote sessions only), Exit-PSSession[1]

  • 在脚本中使用它的唯一可能原因暂停运行脚本,以便进入用户可以在中操作的交互式远程会话。一旦用户退出交互式会话,脚本将继续本地

  • 但是,由于 错误 从 PowerShell 7.2.1 开始实际上不起作用,并且执行意外地 本地 立即继续(这就是您所看到的)- 参见 this answer.

对于自动远程执行,请改用Invoke-Command

  • 它要求你将所有要远程执行的语句以script block{ ... }.

    的形式传给它的-ScriptBlock参数
  • 如果您需要在不同时间向远程计算机传递多个批语句,您可以使用New-PSSession创建一个显式会话对象并将它用于带有 -Session 参数的每个 Invoke-Command 调用(而不是通过 -ComputerName 隐式创建 one-off 会话)。

有关详细信息,请参阅概念性 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 - 在本地和远程会话中都有效 - 没问题。