powershell - 使用 PowerShell 远程复制文件

标签 powershell powershell-2.0

我正在编写一个想要从服务器 A 运行的 PowerShell 脚本。 我想连接到服务器 B 并将文件复制到服务器 A 作为备份。

如果无法完成,那么我想从服务器 A 连接到服务器 B,并将文件复制到服务器 B 中的另一个目录。

我看到 Copy-Item命令,但我不知道如何为其指定计算机名称。

我本以为我可以做类似的事情

Copy-Item -ComputerName ServerB -Path C:\Programs\temp\test.txt -Destination (not sure how it would know to use ServerB or ServerA)

我该怎么做?

最佳答案

PowerShell 版本 5 开始(包含在 Windows Server 2016 downloadable as part of WMF 5 for earlier versions 中),这可以通过远程处理实现。这样做的好处是,即使您出于某种原因无法访问共享,它也能正常工作。

为此,启动复制的本地 session 必须安装 PowerShell 5 或更高版本。远程 session 不需要安装 PowerShell 5 - 它可以与低至 2 的 PowerShell 版本和低至 2008 R2 的 Windows Server 版本配合使用。[1]

从服务器 A 创建到服务器 B 的 session :

$b = New-PSSession B

然后,仍然来自 A:

Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt

将项目复制到 B 是通过 -ToSession 完成的。请注意,这两种情况都使用本地路径;您必须跟踪您所在的服务器。

<小时/>

[1]:从仅具有 PowerShell 2 的远程服务器进行复制或向其复制时,请注意 this bug in PowerShell 5.1 ,在撰写本文时,这意味着递归文件复制不适用于 -ToSession,显然复制根本不适用于 -FromSession

关于powershell - 使用 PowerShell 远程复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10741609/

相关文章:

Jenkins Pipeline 中的 PowerShell 环境变量给出 `org.jenkinsci.plugins.workflow.cps.EnvActionImpl@1b69f5bb:VARIABLE_NAME`

powershell - 导入 CSV GroupBy Sum

c# - 将 Dictionary[String,String] 从 powershell 发送到 TextTransform.exe

mysql - 将数据库查询结果格式化为电子邮件

c# - 在 powershell 和 C# 之间共享变量

powershell - 为 PowerShell Core 脚本使用 .pwsh 而不是 .ps1 扩展名?

syntax - powershell中的条件执行(&&和||)

powershell - 遍历数据库数组以对数据库运行SQL查询

powershell - Stop-Service Cmdlet无法打开存在的服务

c - 从 C 调用的 Powershell 脚本不会打开 OleDb 连接