Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 953
blue18hutthutt Avatar asked Jul 19 '12 16:07

blue18hutthutt


People also ask

Does PowerShell copy item overwrite existing files?

By default when you run the PowerShell Copy-Item cmdlet, it will overwrite the file if it is already exists. Here, we will see an example on PowerShell copy item exclude existing files.

Can I use xcopy in PowerShell?

xcopy is the windows command. It works with both PowerShell and cmd as well because it is a system32 utility command.

How do I copy a file from one location to another in PowerShell?

To copy items in PowerShell, one needs to use the Copy-Item cmdlet. When you use the Copy-Item, you need to provide the source file name and the destination file or folder name. In the below example, we will copy a single file from the D:\Temp to the D:\Temp1 location.


2 Answers

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 
}
like image 113
goric Avatar answered Nov 02 '22 23:11

goric


    Copy-Item C:\Temp\Test1\* C:\Temp\Test2
    Remove-Item "C:\Temp\Test2\*" -recurse

Works too :)

like image 28
PowerShellGirl Avatar answered Nov 03 '22 00:11

PowerShellGirl