首页 > 解决方案 > 使用powershell按顺序重命名pdf文件

问题描述

我有大量需要按顺序重命名的pdf。这些最初被扫描成一个文档,然后提取为单独的文件。提取后,名称变为“444026-444050 1”、“444026-444050 2”等。我正在尝试重命名所有文件以匹配文档编号(“444026-444050 1”将变为“444026”)。

我找到了可以在 Powershell 中使用的以下代码行,但似乎超过 9 个文件都有问题!一旦我尝试了 10 个文件,只有第一个文件被正确保存。其余的变得混乱(文件 444027 有文件 444035 的内容,然后文件 444028 有 444027,444029 有 444028,等等)

我想循环存在某种问题,但很难修复它。

有人可以帮忙吗?谢谢

Dir *.pdf | ForEach-Object  -begin { $count=26 }  -process { rename-item $_ -NewName "4440$count.pdf"; $count++ }

标签: powershellrenamesequential

解决方案


好的。让我们看看这是否让每个人都开心。也许您应该尝试使用文件的备份副本。

# make some test files in a new folder
# 1..20 | foreach {
#   if (! (test-path "44026-44050 $_.pdf")) { 
#     echo "44026-44050 $_" > "44026-44050 $_.pdf" }
# }

# rename and pad the first 9 old filenames with a 0 before the last digit for sorting
# is it less than 100 files?
1..9 | foreach {
  ren "44026-44050 $_.pdf" "44026-44050 0$_.pdf" -whatif
}

# make dir complete first with parentheses for powershell 5
# pad $count to 2 digits
# take off the -whatif if it looks ok
(dir *.pdf) | foreach { $count = 1 } {
    $padded = $count | foreach tostring 00
    rename-item $_ -newname 4440$padded.pdf -whatif; $count++ }

推荐阅读