2013-07-24 39 views
15

我很努力地在下面得到这个脚本努力复制正确结构中的文件夹和子文件夹中的文件(作为源服务器)。复制项目使用Powershell在源服务器的相同目录结构中的文件夹和子文件夹中的文件

比方说,有以下提到的文件夹:

主文件夹:文件AAA,文件bbb的

子文件夹中的:文件1,文件2,文件3

子文件夹B:文件4,文件5,文件6使用

脚本:

Get-ChildItem -Path \\Server1\Test -recurse | ForEach-Object { 
Copy-Item -LiteralPath $_.FullName -Destination \\server2\test | 
Get-Acl -Path $_.FullName | Set-Acl -Path "\\server2\test\$(Split-Path -Path $_.FullName -Leaf)" 

} 

输出: 文件AAA,文件bbb的

子文件夹中的(空文件夹)

子文件夹B(空文件夹)

文件1,文件2,文件3,文件4,文件5,文件6。

我想将文件复制到各自的文件夹(如源文件夹)。任何进一步的帮助,高度赞赏。

+0

如果你要复制的一切,Kevin_的答案应该工作。如果你需要过滤输入,请参阅http://stackoverflow.com/questions/17788208/moving-jpgs-using-powershell-script-with-variable-directories – Eris

+0

@Kevin_完整示例使用** robocopy **在PowerShell中? – Kiquenet

回答

41

这可以使用Copy-Item来完成。不需要使用Get-Childitem。我认为你只是在推翻它。

Copy-Item -Path C:\MyFolder -Destination \\Server\MyFolder -recurse -Force 

我刚测试过它,它为我工作。

+20

我发现如果您多次运行该命令,该命令的行为会发生变化。第一次,它会将所有内容复制到\\ Server \ MyFolder。第二次和以后,它会将所有内容复制到\\ Server \ MyFolder \ MyFolder – thecodefish

+0

@thecodefish我也注意到了这一点,但只有当目标目录不存在时才会发生。使用New-Item -ItemType Directory -Path $ target -Force | Out-Null将解决问题。 -Force开关只会在不存在的情况下创建目录,Out-Null不会污染您的输出。 – Indy411

+0

也可以使用像'Copy-Item **/*。txt -Destination C:/ destination'这样的模式匹配。 –

-2

我想要一个解决方案来复制特定日期和时间后修改的文件,这意味着我不需要使用通过过滤器传递的Get-ChildItem。下面是我想到的:

$SourceFolder = "C:\Users\RCoode\Documents\Visual Studio 2010\Projects\MyProject" 
$ArchiveFolder = "J:\Temp\Robin\Deploy\MyProject" 
$ChangesStarted = New-Object System.DateTime(2013,10,16,11,0,0) 
$IncludeFiles = ("*.vb","*.cs","*.aspx","*.js","*.css") 

Get-ChildItem $SourceFolder -Recurse -Include $IncludeFiles | Where-Object {$_.LastWriteTime -gt $ChangesStarted} | ForEach-Object { 
    $PathArray = $_.FullName.Replace($SourceFolder,"").ToString().Split('\') 

    $Folder = $ArchiveFolder 

    for ($i=1; $i -lt $PathArray.length-1; $i++) { 
     $Folder += "\" + $PathArray[$i] 
     if (!(Test-Path $Folder)) { 
      New-Item -ItemType directory -Path $Folder 
     } 
    } 
    $NewPath = Join-Path $ArchiveFolder $_.FullName.Replace($SourceFolder,"") 

    Copy-Item $_.FullName -Destination $NewPath 
} 
0

如果你想镜像从源到目的地相同的内容,请尝试下面的一个。

function CopyFilesToFolder ($fromFolder, $toFolder) { 
    $childItems = Get-ChildItem $fromFolder 
    $childItems | ForEach-Object { 
     Copy-Item -Path $_.FullName -Destination $toFolder -Recurse -Force 
    } 
} 

测试:

CopyFilesToFolder "C:\temp\q" "c:\temp\w" 
相关问题