【问题标题】:How can I execute a command in each subdirectory of a folder?如何在文件夹的每个子目录中执行命令?
【发布时间】:2018-12-24 06:44:37
【问题描述】:

我有一个文件夹,其中包含更多文件夹。

我希望将某个“级别”的所有文件上移一个。

例如我有:

  • 父文件夹\Actor1\Movie\HighRes\HighresMovie.mp4
  • 父文件夹\Actor1\Movie\LowresMovie.mp4
  • 父文件夹\Actor2\Movie\HighRes\HighresMovie.mp4
  • 父文件夹\Actor2\Movie\LowresMovie.mp4

但我希望它看起来像:

  • 父文件夹\Actor1\Movie\HighresMovie.mp4
  • 父文件夹\Actor1\Movie\LowresMovie.mp4
  • 父文件夹\Actor2\Movie\HighresMovie.mp4
  • 父文件夹\Actor2\Movie\LowresMovie.mp4

这是一个包含大约 1000 个“演员”文件夹的庞大文件夹。

我目前有这个命令行命令部分工作:

for /f "delims==" %i in ('dir /a:d /b') do for /f "delims==" %f in ('dir "%i" /a:d /b') do (move "%i\%f\*.*" "%i"&&rd "%i\%f" /s /q)

我可以从“Actor”文件夹中的命令行运行此命令,它完全符合我的要求。现在我希望能够从“ParentFolder”运行它,并将相同的命令应用于我拥有的每个“Actor”文件夹。

【问题讨论】:

  • 您要移动的文件是否始终位于HighRes 目录中?
  • 是的,它总是在一个名为那个的目录中。制作一个强大的命令可以从该级别的深处获取所有文件会很好,但对于这种情况是的。
  • 对我已有的代码是否有某种快速修改可以让它看起来更深一个文件夹?
  • 我已经很久没有做 BAT/CMD 的东西了,我完全不知道你发布的代码的细节是什么。 [脸红]所以我不能告诉你任何事情。
  • 是的,我刚刚从其他人那里在线找到了代码,它在我所说的单个实例中工作。如果您知道其他方法,将不胜感激!

标签: windows powershell batch-file file-io command-line


【解决方案1】:

这将获取$TopDir 树中与*.mp4 匹配并且路径名中有HighRes 的文件列表。然后它遍历列表,获取父目录名称,并将文件移动到该父目录。

当你准备好实际操作时删除-WhatIf ... [grin]

$TopDir = "$env:TEMP\ParentFolder"
$Filter = '*.mp4'
$SourceDir = 'HighRes'

$MoveFileList = Get-ChildItem -LiteralPath $TopDir -Filter $Filter -Recurse -File |
    Where-Object {$_.DirectoryName -match $SourceDir}

foreach ($MFL_Item in $MoveFileList)
    {
    $DestDir = Split-Path -Path $MFL_Item.DirectoryName -Parent
    Move-Item -LiteralPath $MFL_Item.FullName -Destination $DestDir -WhatIf
    }

输出[重新格式化以便于阅读] ...

What if: Performing the operation
    "Move File"
    on target
    "Item: C:\Temp\ParentFolder\Actor1\Movie\HighRes\HighresMovie.mp4
     Destination: C:\Temp\ParentFolder\Actor1\Movie\HighresMovie.mp4".
What if: Performing the operation
    "Move File"
    on target
    "Item: C:\Temp\ParentFolder\Actor2\Movie\HighRes\HighresMovie.mp4
     Destination: C:\Temp\ParentFolder\Actor2\Movie\HighresMovie.mp4".

【讨论】:

  • 效果很好!有没有办法以某种方式清理空文件夹?
  • @TylerBoodman - 是的!在Move-Item 行之后和最后一个} 之前添加Remove-Item -LiteralPath $DestDir -WhatIf
  • @TylerBoodman - 不客气!很高兴能帮上忙……[grin]
猜你喜欢
  • 2022-11-02
  • 2010-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
相关资源
最近更新 更多