Search code examples
powershellpowershell-2.0powershell-ise

Copy-Item / Remove-Item child-content only without root folder?


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?


Solution

  • 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 
    }