使用Powershell远程复制文件

时间:2012-05-24 16:30:38

标签: powershell powershell-v2.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)

我该怎么做?

5 个答案:

答案 0 :(得分:81)

  

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

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

答案 1 :(得分:62)

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显然无法复制。

答案 2 :(得分: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

答案 3 :(得分: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)

答案 4 :(得分: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

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