使用PowerShell重命名POS系统文件:调整格式提升可读性
解决POS系统生成文件的PowerShell重命名问题
需求分析
需要将POS生成的特定格式文件名转换为易读易排序的格式:
StoreClose20230122220648→2023-01-22 220648 Store CloseTillSummeryClose20230122220648→2023-01-22 220648 Till Summery Close
核心需求拆解:
- 拆分文件名中的文本驼峰部分为空格分隔的单词
- 将**14位数字日期时间(YYYYMMDDHHMMSS)**格式化为
YYYY-MM-DD HHMMSS - 按「日期时间 + 空格 + 文本 + 扩展名」的顺序重组文件名
修正后的完整代码
$SRC = "$env:USERPROFILE\Desktop\From Here" $DST = "$env:USERPROFILE\Desktop\To Here" $EXT = "*.pdf", "*.log", "*.txt" $SRC_EXST = Test-Path -Path $SRC -ErrorAction SilentlyContinue $DST_EXST = Test-Path -Path $DST -ErrorAction SilentlyContinue $CWD = $PSScriptRoot if (!$SRC_EXST) { "$(Get-Date) 无效的源路径 [$SRC]." | Out-File -FilePath "$CWD\log.txt" -Encoding utf8 -Append exit } if (!$DST_EXST) { "$(Get-Date) 无效的目标路径 [$DST]." | Out-File -FilePath "$CWD\log.txt" -Encoding utf8 -Append exit } $files = Get-ChildItem -Path $SRC -Include $EXT -File foreach ($file in $files) { $baseName = $file.BaseName $fileExt = $file.Extension # 匹配文件名结构:[驼峰文本][14位日期时间数字] if ($baseName -match '^([A-Za-z]+)(\d{14})$') { $textSegment = $matches[1] $datetimeSegment = $matches[2] # 拆分驼峰命名为空格分隔的单词 $formattedText = ($textSegment -replace '([A-Z])', ' $1').Trim() # 格式化日期时间部分 $formattedDatetime = "{0}-{1}-{2} {3}" -f $datetimeSegment.Substring(0,4), # 年 $datetimeSegment.Substring(4,2), # 月 $datetimeSegment.Substring(6,2), # 日 $datetimeSegment.Substring(8,6) # 时分秒 # 组合新文件名 $newFileName = "$formattedDatetime $formattedText$fileExt" # 将文件移动到目标文件夹并重命名(原地重命名请改用 Rename-Item) Move-Item -Path $file.FullName -Destination (Join-Path $DST $newFileName) -Force Write-Output "已处理: $($file.Name) → $newFileName" } else { Write-Output "跳过不符合格式的文件: $($file.Name)" } }
关键逻辑说明
- 正则匹配:
^([A-Za-z]+)(\d{14})$精准捕获文件名中的文本段和14位日期时间段,确保只处理符合格式的文件 - 驼峰拆分:用
-replace '([A-Z])', ' $1'在每个大写字母前插入空格,再通过Trim()移除开头多余空格,实现驼峰转自然语言格式 - 日期格式化:通过
Substring()拆分14位数字为年、月、日、时分秒,再用字符串格式化拼接为易读的日期时间格式 - 文件操作:使用
Move-Item将文件移至目标文件夹并完成重命名,如需原地重命名可替换为Rename-Item -Path $file.FullName -NewName $newFileName -Force
内容的提问来源于stack exchange,提问作者YMH
相关产品推荐
相关产品推荐

