8

Hi I'm struggling mightily with the following - suppose I have the following directory structure C:\Temp\Test1 and C:\Temp\Test2

What I'd like to do is recursively copy the child-contents of C:\Temp\Test1 to C:\Temp\Test2 without copying the actual folder C:\Temp\Test1 ..right now if I use the command

Copy-Item C:\Temp\Test1 C:\Temp\Test2 -Recurse

Will result in C:\Temp\Test2\Test1 and no combination of parameters seems to alleviate the problem

Similarly, when I wish to remove all the child content in C:\Temp\Test2 I wish to only delete the child content and not the actual folder eg

Remove-Item C:\Temp\Test2\ -Recurse

Is removing the \Test2 folder. I've tried so many variations of parameters - how can I accomplish what I am trying to do?

blue18hutthutt
  • 3,191
  • 5
  • 34
  • 57

2 Answers2

8

Take a look at the get-childitem command. You can use this in the pipeline to copy or remove all items underneath the root folders:

# recursively copy everything under C:\Temp\Test1 to C:\Temp\Test2
get-childitem "C:\Temp\Test1" | % { 
    copy-item $_.FullName -destination "C:\Temp\Test2\$_" -recurse 
}

# recursively remove everything under C:\Temp\Test1
get-childitem "C:\Temp\Test1" -recurse | % { 
    remove-item $_.FullName -recurse 
}
goric
  • 11,491
  • 7
  • 53
  • 69
  • 1
    Note that you do not need to wrap the cmdlet calls in a foreach (`... | % { cmdlet $_.FullName ... }`); both [`Copy-Item`](http://go.microsoft.com/fwlink/?LinkID=113292) and [`Remove-Item`](http://go.microsoft.com/fwlink/?LinkID=113373) will automatically accept input from the pipeline. E.g. the second example can be simplified to `Get-ChildItem "$env:temp\Test1" | Remove-Item -Recurse`. – Emperor XLII Aug 23 '12 at 23:34
5
    Copy-Item C:\Temp\Test1\* C:\Temp\Test2
    Remove-Item "C:\Temp\Test2\*" -recurse

Works too :)

Kiryl
  • 180
  • 13
  • copy-item does preserve (even with recurse or container) a folder structure in Test1.... – Falco Alexander Apr 28 '16 at 12:54
  • @FalcoAlexander is right, don't upvote this post it is not right – brechtvhb Jul 02 '18 at 11:18
  • https://superuser.com/questions/1152895/powershell-copy-item-recursively-but-dont-include-folder-name / https://superuser.com/questions/1152895/powershell-copy-item-recursively-but-dont-include-folder-name – edelwater Sep 22 '21 at 11:07