PowerShell实现目录中文件名按指定长度截断后缀
PowerShell批量截断PDF文件名至指定长度(保留前9个字符)
基础实现脚本
适合无重名场景,直接提取文件名前9个字符并保留原扩展名:
# 替换为你的PDF文件所在目录路径 $targetDir = "C:\Your\PDF\Directory" # 获取目录下所有PDF文件 $pdfFiles = Get-ChildItem -Path $targetDir -Filter "*.pdf" foreach ($file in $pdfFiles) { # 截取文件名(不含扩展名)前9个字符,拼接原扩展名 $newFileName = $file.BaseName.Substring(0, 9) + $file.Extension # 组合新文件路径 $newFilePath = Join-Path -Path $targetDir -ChildPath $newFileName # -WhatIf 用于预览操作,确认无误后可移除 Rename-Item -Path $file.FullName -Destination $newFilePath -WhatIf }
关键说明
$file.BaseName:获取不带扩展名的原文件名,例如4616_A411_P05_Ground Floor Plan Zone 6会返回纯文件名部分Substring(0, 9):从字符串起始位置(索引0)截取9个字符,精准得到前9位内容- 保留原扩展名确保文件格式不变,避免变成无格式文件
处理重名的增强脚本
如果截断后出现重复文件名,自动添加序号避免报错:
$targetDir = "C:\Your\PDF\Directory" $pdfFiles = Get-ChildItem -Path $targetDir -Filter "*.pdf" foreach ($file in $pdfFiles) { $truncatedBase = $file.BaseName.Substring(0, 9) $extension = $file.Extension $newFileName = "$truncatedBase$extension" $newFilePath = Join-Path -Path $targetDir -ChildPath $newFileName # 检测重名,若存在则添加序号 $counter = 1 while (Test-Path -Path $newFilePath) { $newFileName = "$truncatedBase($counter)$extension" $newFilePath = Join-Path -Path $targetDir -ChildPath $newFileName $counter++ } Rename-Item -Path $file.FullName -Destination $newFilePath -WhatIf }
新手注意事项
- 操作前务必备份PDF文件,避免误操作导致文件丢失
- 先保留
-WhatIf参数执行脚本,预览重命名计划,确认符合预期后再移除该参数执行实际重命名 - 如果需要递归处理子目录中的PDF文件,给
Get-ChildItem添加-Recurse参数即可
内容的提问来源于stack exchange,提问作者Martin Kennedy
相关产品推荐
相关产品推荐

