2

How can I use copy with multiple filter values?

For example, it works if I specify only 1 value to filter (*.jpg)

Copy-Item -Path Y:\TEST -Recurse -Filter *.jpg -Destination D:\Users\MS5253\Desktop\Lots

This create me a folder (D:\Users\MS5253\Desktop\Lots\TEST) that contains only jpg files

But I also want to filter xml files, I tried this :

Copy-Item -Path Y:\TEST -Recurse -Filter *.jpg,*.xml -Destination D:\Users\MS5253\Desktop\Lots

It gives me an error.

and this : Copy-Item -Path Y:\TEST -Recurse -include "*.jpg","*.xml" -Destination D:\Users\MS5253\Desktop\Lots

It doesn't work...

Thanks for your help, i'm using Windows 7 with Powershell v4.

  • You can't, that parameter does not support an array object. You will have to just use two different commands. – user47078 Jul 20 '15 at 18:06
  • two different commands does not work, because if you have nested folder structure, it will throw errors on inability to create a folder or overwrite folders without merging being called with force – Himura Jul 31 at 12:41
5

If you want all the jpg and xml files into one folder, you could use Get-ChildItem -Include:

Get-ChildItem -Include *.jpg,*.xml -Recurse | ForEach-Object { 
    Copy-Item -Path $_.FullName -Destination D:\Users\MS5253\Desktop\Lots
}
| improve this answer | |
0

If you need to preserve a folder structure, it seems like there's no other way than manual paths management:

function Copy-Filtered {
    param (
        [string] $Source,
        [string] $Target,
        [string[]] $Filter
    )
    $ResolvedSource = Resolve-Path $Source
    $NormalizedSource = $ResolvedSource.Path.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar
    Get-ChildItem $Source -Include $Filter -Recurse | ForEach-Object {
        $RelativeItemSource = $_.FullName.Replace($NormalizedSource, '')
        $ItemTarget = Join-Path $Target $RelativeItemSource
        $ItemTargetDir = Split-Path $ItemTarget
        if (!(Test-Path $ItemTargetDir)) {
            [void](New-Item $ItemTargetDir -Type Directory)
        }
        Copy-Item $_.FullName $ItemTarget
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.