PowerShell脚本从一个服务器的多个文件夹复制相同文件并粘贴到另一台服务器

时间:2019-11-27 10:47:07

标签: powershell

我在服务器“ S01”的多个文件夹"file.config"中有一个名称为(D:\Auth0\file.config, D:\Auth1\file.config, D:\Auth2\file.config.....)的文件。我想从所有Auth文件夹复制此文件,然后使用 PowerShell 粘贴到另一台服务器中。

我想出的一切如下:

$Session = New-PSSession -ComputerName "S01" -Credential "domain\user"
Copy-Item "D:\Auth0\file.config" -Destination "\C:\Backups" -FromSession $Session

此脚本仅从 Auth0 文件夹复制文件,并粘贴到同一服务器的C驱动器中。要从其他文件夹复制,我必须更改文件夹名称并再次运行脚本。

我想运行从所有Auth文件夹复制该文件并将其粘贴到另一台服务器的脚本。 请帮忙。

谢谢

1 个答案:

答案 0 :(得分:2)

您不能在脚本中多次运行Copy-Item命令吗?

$Session = New-PSSession -ComputerName "S01" -Credential "domain\user"
Copy-Item "D:\Auth0\file.config" -Destination "\C:\Backups" -FromSession $Session
Copy-Item "D:\Auth1\file.config" -Destination "\C:\Backups" -FromSession $Session
Copy-Item "D:\Auth2\file.config" -Destination "\C:\Backups" -FromSession $Session

好吧,如果我对您的理解正确,那应该可以:

$DestinationSession = New-PSSession -ComputerName "S01" -Credential "domain\user"
# Is S01 you destination server? And from where are you running this script?
# See the difference between -ToSession and -FromSession
foreach($n in 1..1000)
{
    Copy-Item "D:\Auth$($n)\file.config" -Destination "C:\Backups" -ToSession $DestinationSession
}