跳到主要内容

batch-file-renamer-20261113

收藏0

本地离线批量文件重命名工具,按前缀后缀、查找替换(支持正则)、大小写转换、自动编号和扩展名变更等规则批量改名,默认只试运行预览变更,显式加 -Apply 才真正执行,并自动检测重名冲突,全程不联网。

让 AI 安装

MercuryLV2最新版本 0.1.0更新于 2026-11-13下载 0 次

scripts/Rename-Files.ps1

6.7 KB
1#requires -Version 5.1
2<#
3.SYNOPSIS
4 按规则批量重命名文件,默认试运行预览,-Apply 才真正执行。
5.DESCRIPTION
6 支持前缀/后缀、查找替换(可正则)、大小写转换、连续编号、扩展名变更;
7 默认只输出预览表,不改动磁盘;自动检测重名冲突与非法结果并跳过。全程离线。
8.PARAMETER Path
9 目标目录或文件路径,可传多个。
10.PARAMETER Filter
11 文件通配筛选,默认 *。
12.PARAMETER Recurse
13 递归处理子目录。
14.PARAMETER Prefix
15 文件名(不含扩展名)前缀。
16.PARAMETER Suffix
17 文件名(不含扩展名)后缀。
18.PARAMETER Find
19 需要查找的文本。
20.PARAMETER ReplaceWith
21 替换为的文本,可为空串表示删除。
22.PARAMETER UseRegex
23 Find 按正则解释。
24.PARAMETER Case
25 大小写转换:lower、upper、title、none。
26.PARAMETER Number
27 追加连续编号。
28.PARAMETER NumberStart
29 编号起始值,默认 1。
30.PARAMETER NumberPadding
31 补零位数,0 表示不补零,默认 3。
32.PARAMETER NumberSeparator
33 编号与名称的分隔符,默认 -。
34.PARAMETER NewExtension
35 新扩展名,以点开头。
36.PARAMETER Apply
37 真正执行改名;不传则为试运行。
38.PARAMETER OutFile
39 变更清单输出文件(UTF-8 无 BOM)。
40.EXAMPLE
41 .\Rename-Files.ps1 -Path .\docs -Filter *.pdf -Prefix "2026-" -Number
42.EXAMPLE
43 .\Rename-Files.ps1 -Path .\docs -Filter *.pdf -Prefix "2026-" -Number -Apply
44#>
45[CmdletBinding()]
46param(
47 [Parameter(Mandatory = $true, Position = 0)]
48 [string[]]$Path,
49
50 [string]$Filter = '*',
51 [switch]$Recurse,
52
53 [string]$Prefix = '',
54 [string]$Suffix = '',
55
56 [string]$Find = '',
57 [string]$ReplaceWith = '',
58 [switch]$UseRegex,
59
60 [ValidateSet('lower', 'upper', 'title', 'none')]
61 [string]$Case = 'none',
62
63 [switch]$Number,
64 [int]$NumberStart = 1,
65 [int]$NumberPadding = 3,
66 [string]$NumberSeparator = '-',
67
68 [string]$NewExtension = '',
69
70 [switch]$Apply,
71 [string]$OutFile
72)
73
74Set-StrictMode -Version 2.0
75
76# 收集目标文件
77$targetFiles = New-Object System.Collections.Generic.List[object]
78foreach ($p in @($Path)) {
79 if (-not (Test-Path -LiteralPath $p)) {
80 Write-Warning "路径不存在,已跳过:$p"; continue
81 }
82 $item = Get-Item -LiteralPath $p
83 if ($item.PSIsContainer) {
84 $gciParams = @{ LiteralPath = $item.FullName; File = $true; Force = $true; Filter = $Filter }
85 if ($Recurse) { $gciParams.Recurse = $true }
86 $found = @(Get-ChildItem @gciParams)
87 foreach ($f in $found) { $targetFiles.Add($f) }
88 } else {
89 $targetFiles.Add($item)
90 }
91}
92
93if ($targetFiles.Count -eq 0) {
94 throw '没有找到可处理的文件。'
95}
96
97# 按路径排序,保证编号稳定可预期
98$sorted = @($targetFiles | Sort-Object FullName)
99
100# 非法字符替换
101function Get-SafeName {
102 param([string]$Name)
103 $invalid = [char[]]@('\', '/', ':', '*', '?', '"', '<', '>', '|')
104 $result = $Name
105 foreach ($c in $invalid) { $result = $result.Replace([string]$c, '_') }
106 return $result
107}
108
109function Convert-Case {
110 param([string]$Text, [string]$Mode)
111 switch ($Mode) {
112 'lower' { return $Text.ToLower() }
113 'upper' { return $Text.ToUpper() }
114 'title' {
115 $ti = (Get-Culture).TextInfo
116 return $ti.ToTitleCase($Text.ToLower())
117 }
118 default { return $Text }
119 }
120}
121
122$changes = New-Object System.Collections.Generic.List[object]
123$proposed = @{} # 目标全路径 -> 源路径,用于检测多源同名
124$index = $NumberStart
125
126foreach ($f in $sorted) {
127 $oldName = $f.Name
128 $base = [System.IO.Path]::GetFileNameWithoutExtension($oldName)
129 $ext = [System.IO.Path]::GetExtension($oldName)
130
131 # 1) 查找替换
132 if ($Find -ne '') {
133 if ($UseRegex) {
134 $base = [System.Text.RegularExpressions.Regex]::Replace($base, $Find, $ReplaceWith)
135 } else {
136 $base = $base.Replace($Find, $ReplaceWith)
137 }
138 }
139
140 # 2) 大小写
141 $base = Convert-Case -Text $base -Mode $Case
142
143 # 3) 前缀后缀
144 if ($Prefix -ne '') { $base = $Prefix + $base }
145 if ($Suffix -ne '') { $base = $base + $Suffix }
146
147 # 4) 编号
148 if ($Number) {
149 $numText = if ($NumberPadding -gt 0) {
150 $index.ToString().PadLeft($NumberPadding, '0')
151 } else {
152 [string]$index
153 }
154 $base = "$base$NumberSeparator$numText"
155 $index++
156 }
157
158 # 5) 扩展名
159 if ($NewExtension -ne '') {
160 $ext = if ($NewExtension.StartsWith('.')) { $NewExtension } else { '.' + $NewExtension }
161 }
162
163 $newName = Get-SafeName -Name ($base + $ext)
164 $newFull = Join-Path $f.DirectoryName $newName
165
166 $status = 'RENAME'
167 $note = ''
168
169 if ($newName -eq '') {
170 $status = 'INVALID'; $note = '结果文件名为空'
171 }
172 elseif ($newName -ceq $oldName) {
173 $status = 'SKIP'; $note = '名称未变化'
174 }
175 elseif ($newFull -cne $f.FullName -and (Test-Path -LiteralPath $newFull) -and ($newFull.ToLower() -ne $f.FullName.ToLower())) {
176 $status = 'CONFLICT'; $note = '目标文件已存在'
177 }
178 elseif ($proposed.ContainsKey($newFull.ToLower()) -and $proposed[$newFull.ToLower()] -ne $f.FullName) {
179 $status = 'CONFLICT'; $note = '多个源文件计算出同一目标名'
180 }
181
182 if ($status -eq 'RENAME') {
183 $proposed[$newFull.ToLower()] = $f.FullName
184 if ($Apply) {
185 try {
186 Rename-Item -LiteralPath $f.FullName -NewName $newName -ErrorAction Stop
187 } catch {
188 $status = 'FAILED'; $note = $_.Exception.Message
189 }
190 }
191 }
192
193 $changes.Add([pscustomobject]@{
194 Status = $status
195 OldName = $oldName
196 NewName = $newName
197 Note = $note
198 Directory = $f.DirectoryName
199 })
200}
201
202$table = $changes | Format-Table Status, OldName, NewName, Note -AutoSize | Out-String
203Write-Output $table
204
205$renamed = @($changes | Where-Object { $_.Status -eq 'RENAME' }).Count
206$failed = @($changes | Where-Object { $_.Status -in @('FAILED', 'CONFLICT', 'INVALID') }).Count
207
208$modeText = if ($Apply) { '已执行' } else { '试运行(未改动文件)' }
209"SUMMARY: MODE=$modeText RENAME=$renamed FAILED=$failed TOTAL=$($changes.Count)"
210
211if ($OutFile) {
212 $lines = New-Object System.Collections.Generic.List[string]
213 $lines.Add("# mode: $modeText")
214 foreach ($c in $changes) {
215 $lines.Add("$($c.Status)`t$($c.OldName)`t->`t$($c.NewName)`t$($c.Note)")
216 }
217 [System.IO.File]::WriteAllLines([System.IO.Path]::GetFullPath($OutFile), $lines, (New-Object System.Text.UTF8Encoding($false)))
218 "REPORT_WRITTEN: $([System.IO.Path]::GetFullPath($OutFile))"
219}
220
221if ($Apply -and $failed -gt 0) { exit 1 } else { exit 0 }

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。