Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

user1926332 picture user1926332 · Jul 24, 2013 · Viewed 134.1k times · Source

I am struggling really hard to get this below script worked to copy the files in folders and sub folders in the proper structure (As the source server).

Lets say, there are folders mentioned below:

Main Folder: File aaa, File bbb

Sub Folder a: File 1, File 2, File 3

Sub Folder b: File 4, File 5, File 6

Script used:

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)"

}

Output: File aaa, File bbb

Sub Folder a (Empty Folder)

Sub Folder b (Empty Folder)

File 1, File 2, File 3, File 4, File 5, File 6.

I want the files to get copied to their respective folders (Like the source folders). Any further help is highly appreciated.

Answer

Kevin_ picture Kevin_ · Jul 24, 2013

This can be done just using Copy-Item. No need to use Get-Childitem. I think you are just overthinking it.

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

I just tested it and it worked for me.

edit: included suggestion from the comments

# Add wildcard to source folder to ensure consistent behavior
Copy-Item -Path $sourceFolder\* -Destination $targetFolder -Recurse