如何使用 PowerShell 递归合并/“展平”文件夹结构

int*_*ter 5 powershell directory-structure

我正在寻求帮助来重组许多子文件夹中的大量文件。

示例来源:

folderX
   aaa.txt
   bbb.txt
folderY
   ccc.txt
   folderZ
      ddd.txt
eee.txt
Run Code Online (Sandbox Code Playgroud)

理想结果:

folderX_aaa.txt
folderX_aaa.txt
folderX_bbb.txt
folderY_ccc.txt
folderY_folderZ_ddd.txt
eee.txt
Run Code Online (Sandbox Code Playgroud)

我希望这是有道理的!我正在使用 Plex 来管理一些媒体,它不喜欢用于某些用途的子文件夹(例如 featurettes 目录)。

我想使用 PowerShell,因为我已经对它有点熟悉了 - 但欢迎任何技术或建议。

提前致谢 :)

mkl*_*nt0 8

这是一个单管道解决方案:

$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
Run Code Online (Sandbox Code Playgroud)

-WhatIf 预览移动操作;将其移除以执行实际移动。
正则表达式[/\\]匹配/or\作为路径分隔符,从而使解决方案跨平台。