Powershell:从文件名创建文件夹并将文件移动到这些文件夹

问题描述 投票:0回答:1

C:\Library 包含 3 个文件夹:

“P1”、“P2”、“P3”

C:\Library\P1 包含文件“T1 - P1”

C:\Library\P2 包含文件“T1 - P2”、“T3 - P2”

C:\Library\P3 包含文件“T1-P3”、“T2 - P3”、“T3 - P3”

我想在 C:\Library 中得到 3 个名为“T1”、“T2”和“T3”的新文件夹,这样 k=1, 2, 3,

C:\Library\Tk 包含“Tk - Pj”形式的所有文件,其中 j=1 或 j= 2 或 j=3。

这是我试图组织的一些文件的简化,实际上每个文件夹“Pk”的内容都是未知的,并且索引的范围大于1、2、3。

我有一些基本的 Python 知识,但之前从未使用过 Powershell,只是试图通过查看此网站上的帖子来弄清楚如何完成此任务。

如果您能帮助我解决此问题,我将不胜感激。

我提出了以下应该重复的过程,但不确定如何实施:

  1. 选择C:\Library中第一个非空文件夹,假设是Pi

  2. 选择Pi中的第一个文件,假设是Tj - Pi

  3. 在 C:\Library 中创建一个名为“Tj”的新文件夹。

  4. 将 C:\Library 中“Tj - Pk”形式的所有文件移动到文件夹“Tj”。

  5. 重复步骤 1-4,直到 C:\Library 中的所有文件夹为空。

我尝试过使用cmdlet

Get-ChildItem

也许我应该将它与 -Recurse 和 -Depth 结合起来 但我不确定这是最好的方法。

我看过类似问题的答案,但我不太确定语法。

powershell
1个回答
0
投票

尝试以下方法:

  • 发现
    C:\Library\P*\*
  • 中的所有文件
  • 对于每个文件:
    • 测试对应的
      Tk
      文件夹是否存在,不存在则创建
    • 移动文件
$basePath = "C:\Library"

# loop through each Pj folder
foreach ($pFolder in Get-ChildItem -LiteralPath $basePath -Directory -Filter P*) {
  # loop through each Tk file
  foreach ($file in $pFolder |Get-ChildItem -File -Filter T*) {
    # extract the "Tk" part from the file name
    $targetFolderName = -split $file.Name |Select-Object -First 1
    # calculate destination path
    $targetPath = Join-Path -LiteralPath $basePath -ChildPath $targetFolderName

    # create target folder if it doesn't exist
    if (-not(Test-Path -LiteralPath $targetPath)) {
      New-Item -LiteralPath $targetPath -Type Directory |Out-Null
    }

    # move the file
    $file |Move-Item -Destination $targetPath
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.