51

Trying to index and search for a file within 8K files and 2K folders..

Is there a simple Powershell script that can move all files from folders and/or subfolders into one main folder?

don't need to delete the empty folders but would help.

tackdetack
  • 619
  • 1
  • 5
  • 7
  • 5
    Bring all child files into the parent with "one command": `Get-ChildItem -Path ./ -Recurse -File | Move-Item -Destination ./ ; Get-ChildItem -Path ./ -Recurse -Directory | Remove-Item;` – Vael Victus Apr 12 '20 at 19:38

3 Answers3

79

The fourth example under help -Examples Move-Item[1] is close to what you need. To move all files under the SOURCE directory to the DEST directory you can do this:

Get-ChildItem -Path SOURCE -Recurse -File | Move-Item -Destination DEST

If you want to clear out the empty directories afterwards, you can use a similar command:

Get-ChildItem -Path SOURCE -Recurse -Directory | Remove-Item

[1] https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/move-item

Don Cruickshank
  • 5,641
  • 6
  • 48
  • 48
1

Use .parent for the parent dir. It can be used recursively: .parent.parent

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Dikkie Dik
  • 31
  • 2
1

The other answer led to an error for me because of duplicate files. My code solves this by appending a "_x" to duplicate files. Also the removal should only work, if there are no files left.

$files = Get-ChildItem -Path . -Recurse -File
foreach ($file in $files) {
  $dest = Join-Path . $file.Name
  if (Test-Path $dest) {
    $i = 1
    do {
      $newName = "$($file.BaseName)_$i$($file.Extension)"
      $newDest = Join-Path . $newName
      $i++
    } while (Test-Path $newDest)
    Move-Item -Path $file.FullName -Destination $newDest
  } else {
    Move-Item -Path $file.FullName -Destination $dest
  }
}

Get-ChildItem -Directory | Where-Object {(Get-ChildItem $_ -Recurse -File).count -eq 0} | ForEach-Object {Remove-Item $_ -Recurse}
MySurmise
  • 146
  • 11