Get-ChildItem and Copy-Item explanation

Dejan Dakić picture Dejan Dakić · Feb 13, 2014 · Viewed 27.7k times · Source

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?

Answer

websch01ar picture websch01ar · Feb 13, 2014

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 }