Powershell 3.0: COPY-ITEM Filter or Include options not working

inquisitive_one picture inquisitive_one · Dec 24, 2013 · Viewed 21.8k times · Source

Does the -Filter or -Include parameter work for anyone when using Powershell 3.0? I've tried both of the following commands:

Copy-Item -Path c:\temp -Include "*.TXT" -Destination C:\temp2

and

Copy-Item -Path c:\temp -Filter "*.TXT" -Destination C:\temp2

Actually, for the -Filter option, an empty "temp" folder gets created in c:\TEMP2. I know that the following command works:

Copy-Item -Path c:\temp\*.TXT -Destination C:\temp2

But just wondering if anyone has come across this issue before?

Answer

HAL9256 picture HAL9256 · Dec 24, 2013

This is because the item that you are feeding into Copy-Item is the folder, not the files inside the folder.

When you execute:

Copy-Item -Path c:\temp -Include "*.txt" -Destination C:\temp2

You are saying: Copy Item, where the Path is the folder c:\temp. The only item that is selected to copy is the directory c:\temp. Then we say, only -Include items that match "*.txt". Since the only item (the folder "temp") does not match the pattern, we do nothing.

To prove this, let's change the Include filter to "temp", and re-execute it:

Copy-Item -Path c:\temp -Include "temp" -Destination C:\temp2

Voilà! in the destination folder, we have a new empty folder: c:\temp2\temp. (It's empty because the only item we told it to copy was the folder "temp", we did not tell it to copy anything else)

So for part 2, When you execute:

Copy-Item -Path c:\temp\*.txt -Destination C:\temp2

It works because you are saying, with the *.txt, iterate through all items in the directory that match the pattern *.txt, feed those paths to Copy-Item, and copy to the destination.

To prove this, let's change it, and specify an include filter:

Copy-Item -Path c:\temp\* -Include "*.txt" -Destination C:\temp2

We are saying here, get all items in the folder c:\temp (i.e. we are getting all the items inside the folder c:\temp, and not the folder c:\temp), filter them by only including items that match "*.txt", and copy to the destination.