需要根据文件名将一系列数字文件移动到文件夹

时间:2020-05-04 23:28:24

标签: powershell

我们每天都有成千上万的数据包被扫描到一个临时文件夹中,并使用其数据包编号进行命名。例如:301949.pdf,405311.pdf,481502.pdf等。

我们的文件夹结构内置于千级文件夹和百级子文件夹中,如下所示:

  • Y:\ PACKETS \ 300000 \ 300000-300099
  • Y:\ PACKETS \ 300000 \ 300100-300199
  • Y:\ PACKETS \ 300000 \ 300200-300299
  • Y:\ PACKETS \ 300000 \ 300300-300399
  • Y:\ PACKETS \ 300000 \ 300400-300499
  • Y:\ PACKETS \ 300000 \ 300500-300599
  • Y:\ PACKETS \ 300000 \ 300600-300699
  • Y:\ PACKETS \ 300000 \ 300700-300799
  • Y:\ PACKETS \ 300000 \ 300800-300899
  • Y:\ PACKETS \ 300000 \ 300900-300999
  • Y:\ PACKETS \ 400000 \ 400000-400099
  • Y:\ PACKETS \ 400000 \ 400100-400199
  • Y:\ PACKETS \ 400000 \ 400200-400299
  • Y:\ PACKETS \ 400000 \ 400300-400399
  • Y:\ PACKETS \ 400000 \ 400400-400499
  • Y:\ PACKETS \ 400000 \ 400500-400599
  • Y:\ PACKETS \ 400000 \ 400600-400699
  • Y:\ PACKETS \ 400000 \ 400700-400799
  • Y:\ PACKETS \ 400000 \ 400800-400899
  • Y:\ PACKETS \ 400000 \ 400900-400999
  • Y:\ PACKETS \ 481000 \ 481400-481499
  • Y:\ PACKETS \ 481000 \ 481500-481599
  • Y:\ PACKETS \ 481000 \ 481600-481699
  • Y:\ PACKETS \ 481000 \ 481700-481799
  • Y:\ PACKETS \ 481000 \ 481800-481899
  • Y:\ PACKETS \ 481000 \ 481900-481999
  • Y:\ PACKETS \ 481000 \ 481000-481099
  • Y:\ PACKETS \ 481000 \ 481100-481199
  • Y:\ PACKETS \ 481000 \ 481200-481299
  • Y:\ PACKETS \ 481000 \ 481300-481399

我们需要根据数字文件名将每个数据包移动到正确的文件夹中

例如:

  • 301949.pdf需要输入Y:\ PACKETS \ 301000 \ 301900-301999
  • 405311.pdf需要输入Y:\ PACKETS \ 405000 \ 405300-405399
  • 481502.pdf需要输入Y:\ PACKETS \ 481000 \ 481500-481599

我什至不确定如何开始执行此操作,但我希望这里的人能为您提供帮助!

1 个答案:

答案 0 :(得分:0)

我有点无聊,所以你去:

$SourceFolder = 'Y:\Temp'     # the temporary folder where the pdf files are
$Destination  = 'Y:\PACKETS'  # just the root folder

# you may want to add '-Recurse' if the temp folder contains subfolders
Get-ChildItem -Path $SourceFolder -Filter '*.pdf' -File |
    Where-Object { $_.BaseName -match '^\d{4,}$' } |    # filenames must be numeric and at least 1000 or more 
    ForEach-Object {
        $packet = [int]$_.BaseName                      # create a numeric value from the file's BaseName
        $level1 = [Math]::Floor($packet / 1000) * 1000  # get the 'thousand' value ( 301949 --> 301000 )
        $level2 = [Math]::Floor($packet / 100) * 100    # get the 'hundred' value  ( 301949 --> 301900 )

        # create the complete path to move the file to
        $target = Join-Path -Path $Destination -ChildPath ('{0}\{1}-{2}' -f $level1, $level2, ($level2 + 99))
        # test if this path exists and if not create it
        if (!(Test-Path -Path $target -PathType Container)) {
            $null = New-Item -Path $target -ItemType Directory
        }
        $_ | Move-Item -Destination $target
    }

希望有帮助

相关问题