Home > Software design >  Powershell Flatten dir recursively
Powershell Flatten dir recursively

Time:12-03

Found a couple of semi-related links:

How to merge / 'flatten' a folder structure using PowerShell - recursive

but my ask is that I have a root dir P:/files

which has several layers of sub directories etc I'd like to flatten all of them so that all the -Files are moved just to the root of P:/files

I don't need to be concerned with duplicates as I'll make sure there are non well before this stage.

it looks like I can use powershell to get a list of all the files no matter the level, and then just for-each over them and a move?

Get-ChildItem -LiteralPath P:\files -Directory | Get-ChildItem -Recurse -File

help on the loop?

CodePudding user response:

A single recursive Get-ChildItem that pipes to Move-Item should do:

Get-ChildItem -File -Recurse -LiteralPath P:\files |
  Move-Item -Destination $yourDestination -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

If you need to exclude files directly located in P:\files:

Get-ChildItem -Directory -Recurse -LiteralPath P:\files | Get-ChildItem -File |
  Move-Item -Destination $yourDestination -WhatIf

Note the use of -Directory and -Recurse first, so that all subdirectories in the entire subtree are returned, followed by a non-recursive Get-ChildItem -File call that gets each subdirectory's immediate files only.

  • Related