Reputation: 21
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
Upvotes: 1
Views: 1489
Reputation: 24525
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.
Upvotes: 3
Reputation: 8895
cp -Recurse C:\path\to\search\*.pdf C:\path\to\output\copies
Upvotes: 0
Reputation: 1126
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}
Upvotes: 0