首页 > 解决方案 > 需要根据文件名将一系列数字文件移动到文件夹中

问题描述

我们每天都会将数千个数据包扫描到一个临时文件夹中,并以其数据包编号命名。例如:301949.pdf、405311.pdf、481502.pdf等。

我们的文件夹结构构建为千级文件夹和百级子文件夹,如下所示:

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

例如:

我什至不确定如何开始执行此操作,但我希望这里有人可以提供帮助!

标签: powershell

解决方案


我有点无聊,所以你去:

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

希望有帮助


推荐阅读