1

I have a file structure similar to:

OldLocation/A, OldLocation/B, OldLocation/C, and OldLocation/D

I want to move folders A, B, and D to NewLocation (along with their contents). I have the following code:

    $Copyfiles = Get-ChildItem -Path $folder -Directory -Exclude 'C'



foreach ($item in $Copyfiles)
{

Copy-Item -Path $item -Recurse -Force -Destination $Dest
}

My desired goal is to end up with NewLocation/A/A's stuff, NewLocation/B/B's stuff, NewLocation/D/D's stuff

It seems to almost work, the only hang up is for some reason it only copies the contents of folder A, and not the folder itself. Thus I get NewLoacation/A's stuff, NewLocation/B/B's stuff, and NewLocation/D/D's stuff

How can I fix this?

Andy
  • 207
  • 4
  • 18
  • `Get-ChildItem` gets the content of the folder, not the folder itself. Is this what you mean? Can you post your actual code? It doesn't look like `$Dest` is changing so I assume you could just do `Copy-Item -Path $folder -Recurse -Force -Destination $Dest }` – Nico Nekoru Jul 09 '20 at 22:19
  • @NekoMusume: `-Directory` makes `Get-ChildItem` get directories (folders) themselves. – mklement0 Jul 09 '20 at 22:27
  • @mklement0 So where is the `Get-ChildItem` taking place? `\Oldlocation`? In that case why do you need `-recurse`? Are they all going to the same destination? And why are they excluding `C`? – Nico Nekoru Jul 09 '20 at 22:30
  • Oops, I'm just an idiot... I understand now – Nico Nekoru Jul 09 '20 at 22:32

1 Answers1

2

Make sure that the destination directory exists beforehand, because Copy-Item behaves differently when copying whole directories, depending on whether the destination directory already exists or not:

  • If it doesn't exist, the source directory's contents are copied to the created-on-demand destination directory.

  • If it does exist, the source directory as a whole is copied to the destination directory as a subdirectory.

See this answer for background information.


You can use the following command to ensure that destination directory $Dest exists, using New-Item's -Force switch for desired-state logic: it will create the destination directory on demand (and return a System.IO.DirectoryInfo instance describing either the newly created or the preexisting directory).

$null = New-Item -Type Directory -Force $Dest
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    @Andy: Yes, though I suggest adding `-Force` for desired-state logic: it'll create the destination dir. _on demand_ - please see my update. – mklement0 Jul 10 '20 at 00:31