Dejan Dakić
Dejan Dakić

Reputation: 2448

Get-ChildItem and Copy-Item explanation

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?

Upvotes: 15

Views: 47000

Answers (5)

Andy Wrench
Andy Wrench

Reputation: 91

This works for me:

Get-ChildItem 'c:\source\' -Recurse | % {Copy-Item -Path $_.FullName -Destination 'd:\Dest\' -Force -Container }

Upvotes: 2

websch01ar
websch01ar

Reputation: 2123

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 }

Upvotes: 22

Josh K
Josh K

Reputation: 1

The switches are wrong. They should be:

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

Upvotes: -1

Gauss
Gauss

Reputation: 1148

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.

Upvotes: -1

Manish Kumar
Manish Kumar

Reputation: 113

Here is what worked for me

Get-ChildItem -Path .\ -Recurse -Include *.txt | %{Join-Path -Path $_.Directory -ChildPath $_.Name } | Copy-Item -Destination $to

Upvotes: 3

Related Questions