1
votes

I am trying to copy all .pdf files from all folders and sub folder (dirs. and subdirs).

Folder1
  1.pdf
  2.pdf
Folder1\Foder2\3.pdf
Folder1\Folder2\4.pdf
Folder1\Foder2\Folder3\5.pdf
Folder1\Folder2\Folder3\6.pdf

First I used

 $source = "c:\Folder1\"
 $desti = "D:\foderA\"
 PS> Get-ChildItem -recurse $source -Filter "*.pdf"

It displays all the files in dir and sub dir but when I try to use copy-Item I get the error.

 PS> Get-ChildItem -recurse $source -Filter "*.pdf" | % {Copy-Item $_    -destination $desti}

Error: Copy-Item : Cannot find path 'C:\Folder1\Folder2.... because it does not exist. Error points to source being non-existent. What am I doing wrong? Is it because I have read only on the source drive\Folder?

Thanks

3

3 Answers

3
votes

You can pipe the output objects from Get-ChildItem directly to Copy-Item (i.e., you don't need % [which is an alias for ForEach-Object]); e.g.:

Get-ChildItem -Recurse $source -Filter "*.pdf" -File | Copy-Item -Destination $desti

The -File parameter restricts the search only to files.

0
votes

You almost have it right, $_ is only grabbing the filename, so you lose the path and it tries to use the path your running the script from. Use this instead which will keep the full path.

Get-ChildItem -Recurse $source -Filter "*.pdf" | % {Copy-Item $_.FullName -Destination $desti}

0
votes
cp -Recurse C:\path\to\search\*.pdf C:\path\to\output\copies