Search code examples
powershellcopy-item

ForEach-Object/Copy-Item only content (not the folder itself!)


I have code that looks for folders and afterwards it looks for the criteria I am telling it. So far so good. Then I got a ForEach-Object with a Copy-Item $_.Fullname in it. The code itself is working and spitting no errors, but I don't want to copy the folder itself + its content. I just want to copy the content of the folder. I already tried things like $_.Fullname/* and so on.

Here's how my code looks like:

Get-ChildItem -Path $DestinationBackup | Where {
    $_.Name -like "$BackupName_Differential3*"
} | ForEach-Object {
    Copy-Item -Path $_.FullName -Recurse -Destination $Differential_Destination -Force
}

Edit 1:

My Folder structure looks like this:

M143                       ← (Root Folder)
├─Backups                  ← (Folder, here are Backups stored)
│ ├─Fullbackup...
│ ├─Incrementalbackup...   ← Copy Content of this folder, without folder)
│ └─Differentialbackup...  ← (Into this folder)
└─Backup_Script.ps1

Solution

  • This ...

    Copy-Item -Path $_.FullName -Recurse
    

    ... is your issue. The below should be what you wanted.

    (Get-ChildItem -Path E:\BackUps -Recurse).FullName
    

    Results before Copy

    E:\BackUps\Differential
    E:\BackUps\Full
    E:\BackUps\Incremental
    E:\BackUps\Incremental\IncBU001.bkp
    E:\BackUps\Incremental\IncBU002.bkp
    E:\BackUps\Incremental\IncBU003.bkp
    
    Copy-Item -Path 'E:\BackUps\Incremental\*' -Destination 'E:\BackUps\Differential'
    
    (Get-ChildItem -Path E:\BackUps -Recurse).FullName
    

    Results after copy

    E:\BackUps\Differential
    E:\BackUps\Full
    E:\BackUps\Incremental
    E:\BackUps\Differential\IncBU001.bkp
    E:\BackUps\Differential\IncBU002.bkp
    E:\BackUps\Differential\IncBU003.bkp
    E:\BackUps\Incremental\IncBU001.bkp
    E:\BackUps\Incremental\IncBU002.bkp
    E:\BackUps\Incremental\IncBU003.bkp