1

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

May be add -file in gci (if directory contain .pdf) ;)
Works with or without %
@BharatPatel that may be, but not necessary in this case.
0

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}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.