powershell - 需要根据文件名将一系列数字文件移动到文件夹中
问题描述
我们每天都会将数千个数据包扫描到一个临时文件夹中,并以其数据包编号命名。例如:301949.pdf、405311.pdf、481502.pdf等。
我们的文件夹结构构建为千级文件夹和百级子文件夹,如下所示:
- Y:\包\300000\300000-300099
- Y:\数据包\300000\300100-300199
- Y:\数据包\300000\300200-300299
- Y:\包\300000\300300-300399
- Y:\数据包\300000\300400-300499
- Y:\包\300000\300500-300599
- Y:\数据包\300000\300600-300699
- Y:\包\300000\300700-300799
- Y:\数据包\300000\300800-300899
- Y:\包\300000\300900-300999
- Y:\数据包\400000\400000-400099
- Y:\数据包\400000\400100-400199
- Y:\数据包\400000\400200-400299
- Y:\数据包\400000\400300-400399
- Y:\数据包\400000\400400-400499
- Y:\数据包\400000\400500-400599
- Y:\数据包\400000\400600-400699
- Y:\数据包\400000\400700-400799
- Y:\数据包\400000\400800-400899
- Y:\数据包\400000\400900-400999
- Y:\数据包\481000\481400-481499
- Y:\数据包\481000\481500-481599
- Y:\包\481000\481600-481699
- Y:\数据包\481000\481700-481799
- Y:\数据包\481000\481800-481899
- Y:\数据包\481000\481900-481999
- Y:\数据包\481000\481000-481099
- Y:\数据包\481000\481100-481199
- Y:\包\481000\481200-481299
- Y:\数据包\481000\481300-481399
我们需要根据其数字文件名将每个数据包移动到正确的文件夹中:
例如:
- 301949.pdf需要进入Y:\PACKETS\301000\301900-301999
- 405311.pdf需要进入Y:\PACKETS\405000\405300-405399
- 481502.pdf 需要进入 Y:\PACKETS\481000\481500-481599
我什至不确定如何开始执行此操作,但我希望这里有人可以提供帮助!
解决方案
我有点无聊,所以你去:
$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
}
希望有帮助
推荐阅读
- javascript - 以编程方式在不同浏览器中可视化您的 html
- kubernetes - GKE 入口资源无法正常工作。收到 404 错误
- azure-resource-manager - 用于分配策略的 arm 模板中的错误
- node.js - Azure Functions 使 HTTP 连接保持活动状态
- python - 如何使用列表的一部分创建变量
- python - 如何使用哈希 md5 方法在 pyspark 数据帧中查找重复项?
- c# - 如何覆盖 API 路由名称?
- typescript - 泛型数组的必需和部分
- python-3.x - Python中另一个函数的函数调用
- javascript - object 选项中的对象