Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 785
inquisitive_one Avatar asked Dec 24 '13 15:12

inquisitive_one


People also ask

Does xcopy work in PowerShell?

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

Does copy item overwrite?

The Copy-Item cmdlet has the Container parameter set to $false . This causes the contents of the source folder to be copied but doesn't preserve the folder structure. Notice that files with the same name are overwritten in the destination folder.

How do I copy a folder and contents in PowerShell?

To copy the contents of the folder to the destination folder in PowerShell, you need to provide the source and destination path of the folder, but need to make sure that you need to use a wildcard (*) character after the source path, so the entire folder content gets copied.


1 Answers

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.

like image 93
HAL9256 Avatar answered Oct 17 '22 04:10

HAL9256