Rauhe
Rauhe

Reputation: 77

Powershell in windows 8

I am trying to copy a folder structure to another location as backup. I would also like to exclude file types that are not interesting from the copy. I can do this using XCOPY in a BAT file, but would like to do it using PowerShell (just to try it).

Test Folder Structure:

c:\src  
c:\src\t1.txt  
c:\src\folder1  
c:\src\folder1\t2.txt  

I have come up with this PowerShell script:

Copy-Item C:\src\ C:\dst\ -recurse

This gives the expected output if run once:

c:\dst  
c:\dst\t1.txt  
c:\dst\folder1  
c:\dst\folder1\t2.txt  

If the same script is run twice the folder structure looks like this:

c:\dst  
c:\dst\t1.txt  
c:\dst\folder1  
c:\dst\folder1\t2.txt  
c:\dst\src  
c:\dst\src\t1.txt  
c:\dst\src\folder1  
c:\dst\src\folder1\t2.txt 

Ie. it copies the src folder into the destination folder. I would expect the script to behave the same every time it has been run, but I simply can not fathom what PowerShell is doing here?

Upvotes: 1

Views: 101

Answers (3)

goTo-devNull
goTo-devNull

Reputation: 9372

Someone filed a bug report here, but no resolution:

https://connect.microsoft.com/PowerShell/feedback/details/809855/subfolder-bug-with-command-copy-item-c-folder-c-folder2-recurse-when-done-more-times

You could try:

$testPath = Join-Path $dst (Split-Path $src -leaf);
if (-not (Test-Path $testPath)) { Copy-Item $src $dst -recurse }

or using brute force:

Copy-Item $src $dst -recurse -force

On my system, Win7/PowerShell 2 using only the -recurse parameter, the second run properly throws an error indicating the directory already exists. But FWIW the bug report above and a couple of other places I've seen on the Internet show the same behavior you're seeing with PowerShell 2 as well (creating the extra sub-directories).

Upvotes: 0

arco444
arco444

Reputation: 22881

Does this help?

Copy-Item C:\src\* C:\dst\ -recurse

Without the glob *, you're instructing powershell to copy the entire src directory into dst recursively, so it will also copy the src directory itself. Having the * should avoid this behaviour.

Upvotes: 0

Jimbo
Jimbo

Reputation: 2537

xcopy C:\src\*.* C:\dst\ /s /i 

Upvotes: 1

Related Questions