【问题标题】:Sorting files into directories with powershell使用 powershell 将文件排序到目录中
【发布时间】:2021-08-20 09:31:18
【问题描述】:

我有以下问题,如果我能在这方面得到一些帮助,我将不胜感激。我不断地将 xml 文件流放到一个文件夹中。 XML 文件名可能如下所示。它只上升到 1005。

1001.order-asdf1234.xml
1002.order-asdf4321.xml

我想将文件分类到不基于文件名的唯一命名文件夹中。一个例子是

C:\Directory Path...\Peter (All files starting with 1001 go in there)
C:\Directory Path...\John (All files starting with 1002 go there)

如何创建批处理或 powershell 脚本以将文件连续分类到指定文件夹中?由于我只有 5 个文件夹,我想简单地为每个文件夹指定目标文件夹,并且没有复杂的循环,但我不知道该怎么做。

【问题讨论】:

标签: windows powershell directory


【解决方案1】:

最简单的方法是创建一个查找哈希表,您可以在其中定义哪个前缀 ('1001' .. '1005') 映射到哪个目标文件夹:

# create a Hasthable to map the digits to a foldername
$folderMap = @{
    '1001' = 'Peter'
    '1002' = 'John'
    '1003' = 'Lucretia'
    '1004' = 'Matilda'
    '1005' = 'Henry'
}

# set source and destination paths
$rootFolder = 'X:\Where\the\files\are'
$destination = 'Y:\Where\the\files\should\go'

# loop over the files in the root path
Get-ChildItem -Path $rootFolder -Filter '*.xml' -File | 
Where-Object { $_.BaseName -match '^\d{4}\.' } | 
ForEach-Object {
    $prefix = ($_.Name -split '\.')[0]
    $targetPath = Join-Path -Path $destination -ChildPath $folderMap[$prefix]
    $_ | Move-Item -Destination $targetPath -WhatIf
}

如果您对屏幕上显示的结果感到满意,请移除-WhatIf 安全开关

【讨论】:

    【解决方案2】:

    您可以使用switch 语句根据文件名的第一部分来决定目标文件夹:

    $files = Get-ChildItem path\to\folder\with\xml\files -Filter *.xml
    switch($files)
    {
      {$_.Name -like '1001*'} {
        $_ |Move-Item -Destination 'C:\path\to\Peter'
      }
    
      {$_.Name -like '1002*'} {
        $_ |Move-Item -Destination 'C:\path\to\John'
      }
    
      {$_.Name -like '1003*'} {
        # etc...
      }
    
      default {
        Write-Warning "No matching destination folder for file '$($_.Name)'"
      }
    }
    

    如果您对循环改变主意,我的偏好是将映射存储在哈希表中并循环遍历每个文件的条目:

    $files = Get-ChildItem path\to\folder\with\xml\files -Filter *.xml
    
    $targetFolders = @{
      '1001' = 'C:\path\to\Peter'
      '1002' = 'C:\path\to\John'
      '1003' = 'C:\path\to\Paul'
      '1004' = 'C:\path\to\George'
      '1005' = 'C:\path\to\Ringo'
    }
    
    foreach($file in $files){
      $targetFolder = $targetFolders.Keys.Where({$file.Name -like "${_}*"}, 'First')
    
      $file |Move-Item -Destination $targetFolder
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-31
      • 2021-11-16
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多