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

2024-04-25

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

示例来源:

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

理想结果:

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

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

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

提前致谢 :)


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

$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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐