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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dejan Dakić
  • 2,418
  • 2
  • 25
  • 39
  • what is the difference? the second script is not copying recursively? here one guy helped me using % foreach to copy all output http://stackoverflow.com/questions/17972783/how-to-use-the-copy-item-cmdlet-correctly – RayofCommand Feb 13 '14 at 11:26

5 Answers5

21

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 }
websch01ar
  • 2,103
  • 2
  • 13
  • 22
  • 4
    shouldn't `gci $from -Recurse` get all files from directory and them pipe thru – Dejan Dakić Feb 13 '14 at 13:55
  • 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 }` – kumarharsh Mar 09 '16 at 12:01
  • 1
    You are correct kumar_harsh that I neglected the $_ in my original answer. I've made this slight revisions. – websch01ar Mar 09 '16 at 16:38
3

Here is what worked for me

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

This works for me:

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

The switches are wrong. They should be:

gci -Path $from -Recurse | copy-item -Destination  $to -Force -Container
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Josh K
  • 1
  • 1
-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.

Gauss
  • 1,108
  • 14
  • 13