使用Powershell远程复制文件

问题描述 投票:79回答:5

我正在编写一个我想从服务器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 powershell-v2.0
5个回答
82
投票

只需使用管理共享即可在系统之间复制文件。这种方式更容易。

Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt;

通过使用UNC路径而不是本地文件系统路径,可以帮助确保您的脚本可以从具有这些UNC路径访问权限的任何客户端系统执行。如果您使用本地文件系统路径,那么您将转向在特定计算机上运行脚本。

这仅适用于PowerShell会话在具有两个管理共享权限的用户下运行时。我建议在服务器B上使用常规网络共享,只读访问所有人,只需调用(从服务器A):

Copy-Item -Path "\\\ServerB\SharedPathToSourceFile" -Destination "$Env:USERPROFILE" -Force -PassThru -Verbose

63
投票

从PowerShell版本5开始(包括在Windows Server 2016中,downloadable as part of WMF 5 for earlier versions),这可以通过远程处理实现。这样做的好处是,无论出于何种原因,您都无法访问共享。

为此,启动复制的本地会话必须安装PowerShell 5或更高版本。远程会话不需要安装PowerShell 5 - 它适用于低至2的PowerShell版本,以及低至2008 R2的Windows Server版本。[1]

从服务器A,创建到服务器B的会话:

$b = New-PSSession B

然后,仍然来自A:

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

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


[1]:当从具有PowerShell 2的远程服务器复制时,请注意this bug in PowerShell 5.1,在撰写本文时,表示递归文件复制不适用于-ToSession,显然复制根本不适用于-FromSession


36
投票

为什么不使用net useNew-PSDrive来创建新驱动器。

New-PsDrive:创建一个仅在PowerShell环境中可见的新PsDrive:

New-PSDrive -Name Y -PSProvider filesystem -Root \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy

净使用:在操作系统的所有部分创建一个可见的新驱动器。

Net use y: \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy

13
投票

如果远程文件需要访问您的凭据,您可以使用cmdlet New-Object生成System.Net.WebClient对象以“远程复制文件”,如此

$Source = "\\192.168.x.x\somefile.txt"
$Dest   = "C:\Users\user\somefile.txt"
$Username = "username"
$Password = "password"

$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)

$WebClient.DownloadFile($Source, $Dest)

或者,如果您需要上传文件,可以使用UploadFile

$Dest = "\\192.168.x.x\somefile.txt"
$Source   = "C:\Users\user\somefile.txt"

$WebClient.UploadFile($Dest, $Source)

0
投票

上述答案都不适合我。得到这个错误:

Copy-Item : Access is denied
+ CategoryInfo          : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>   
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

所以这对我来说:

netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes

然后从我的主机我的机器在运行框中只执行此操作\ {ip of nanoserver} \ C $

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