Search code examples
powershelldirectory-structure

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


I'm looking for help restructuring a large number of files within many subfolders.

Example source:

folderX
   aaa.txt
   bbb.txt
folderY
   ccc.txt
   folderZ
      ddd.txt
eee.txt

Ideal result:

folderX_aaa.txt
folderX_aaa.txt
folderX_bbb.txt
folderY_ccc.txt
folderY_folderZ_ddd.txt
eee.txt

I hope that makes sense! I'm using Plex to manage some media and it doesn't like subfolders for certain uses (eg featurettes directory).

I'd like to use PowerShell because I'm already kinda familiar with it - but any techniques or suggestions are welcome.

Thanks in advance :)


Solution

  • Here's a single-pipeline solution:

    $targetDir = Convert-Path '.' # Get the current (target) directory's full path.
    
    Get-ChildItem -LiteralPath $targetDir -Directory | # Loop over child dirs.
    Get-ChildItem -Recurse -File -Filter *.txt | # Loop over all *.txt files in subtrees of child dirs.
    Move-Item -Destination { # Move to target dir.
      # Construct the full target path from the target dir.
      # and the relative sub-path with path separators replaced with "_" chars.
      Join-Path $targetDir `
                ($_.Fullname.Substring($targetDir.Length + 1) -replace '[/\\]', '_') 
    } -Whatif
    

    -WhatIf previews the move operations; remove it to perform actual moving.
    Regex [/\\] matches / or \ as the path separator, so as to make the solution cross-platform.