Get-ChildItem and Copy-Item explanation
Asked Answered
L

5

15

Why does

gci $from -Recurse | copy-item -Destination  $to -Recurse -Force -Container

not behave in the same way as

copy-item $from $to -Recurse -Force

?

I think it should be the same, but somehow it's not. Why?

Leontine answered 13/2, 2014 at 9:39 Comment(1)
what is the difference? the second script is not copying recursively? here one guy helped me using % foreach to copy all output #17973283Sidneysidoma
C
22

You are not looping over each item in the collection of files/folders, but passing the last value to the pipe. You need to use Foreach-item or % to the Copy-Item command. From there, you also do not need the second -recurse switch as you already have every item in the GCI.

try this:

gci $from -Recurse | % {copy-item -Path $_ -Destination  $to -Force -Container }
Championship answered 13/2, 2014 at 11:33 Comment(3)
shouldn't gci $from -Recurse get all files from directory and them pipe thruBronchitis
Isn't the copy-item missing a $_? This is not running for me in PS 5.0 The actual command is: gci $from -Recurse | % { copy-item $_ -Destination $to -Force }Macropterous
You are correct kumar_harsh that I neglected the $_ in my original answer. I've made this slight revisions.Championship
A
3

Here is what worked for me

Get-ChildItem -Path .\ -Recurse -Include *.txt | %{Join-Path -Path $_.Directory -ChildPath $_.Name } | Copy-Item -Destination $to
Aubervilliers answered 25/11, 2014 at 23:49 Comment(1)
No need to Join-Path, use $_.FullName in Copy-Item instead.Mormon
A
2

This works for me:

Get-ChildItem 'c:\source\' -Recurse | % {Copy-Item -Path $_.FullName -Destination 'd:\Dest\' -Force -Container }
Agribusiness answered 11/10, 2019 at 10:46 Comment(2)
Please include an explanation of why this answers the question.Aili
perhaps it doesn't directly but might be helpful to those wishing to understand more about the various ways in which you can achieve the same outcome in different ways.Agribusiness
C
-1

The switches are wrong. They should be:

gci -Path $from -Recurse | copy-item -Destination  $to -Force -Container
Cutin answered 26/5, 2015 at 6:20 Comment(0)
P
-1

To loop all items, this should work:

gci -Path $from -Recurse | % { $_ | copy-item -Destination  $to -Force -Container}

Just do the foreach and pipe each item again.

Palmy answered 23/9, 2015 at 11:47 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.