I am trying to find any files that begin with ADRUPD and then copy them to first location, and then move them to second location. I can confirm the $directory paths are all correct however when I run the below, it only copies the files in to the first location and then errors with:
"Copy-Item : Cannot overwrite the item with itself"
Code:
Get-ChildItem -File -Path $directory -Filter "ADRUPD_*" -Recurse | Copy-Item -Destination $directory2 -PassThru | Move-Item -Destination $directory1
Any assistance with the correct input would be greatly appreciated.
CodePudding user response:
I wouldn't recommend you to perform copy / moving operations in one pipeline as you're currently doing. Here is an example of how you can do it with a foreach
loop.
Code below does not handle file collision, if there is a file with the same name in either of the destination folders this will error out.
$origin = 'origin/path'
$copyDir = 'path/to/copyDir/'
$moveDir = 'path/to/MoveDir/'
foreach($file in Get-ChildItem -File -Path $origin -Filter "ADRUPD_*" -Recurse) {
Copy-Item -LiteralPath $file.FullName -Destination $copyDir
Move-Item -LiteralPath $file.FullName -Destination $moveDir
}
As aside, I'm assuming you want to move the files from $origin
to $moveDir
since it's what's logical. On your code, when you do:
Copy-Item -Destination $directory2 -PassThru
You're passing the copied item's path through the pipeline and performing a moving operation over that file which I don't believe is what you are looking to do.