使用PowerShell读取index.xml批量重命名通话录音WAV文件
PowerShell 批量重命名通话录音实现方案
实现思路
- 读取目标目录下的
index.xml索引文件,自动过滤无效录音条目 - 将XML内的日期字段转换为要求的
MM-DD-YYYY格式 - 拼接生成标准文件名,自动处理重名冲突与文件名非法字符问题
- 批量执行重命名操作
完整代码
# 定义通话录音存放目录 $archivePath = "C:\Call Archive\" # 读取XML索引文件 $xml = [xml](Get-Content (Join-Path $archivePath "index.xml") -Encoding UTF8) # 遍历所有有效录音条目,跳过无效记录 $xml.all.recording_index.day_index.recording | Where-Object { $_.filename -notlike "warning:*" -and $_.filesize -ne "0" -and $_.source -and $_.destination } | ForEach-Object { # 原始文件路径 $oldName = $_.filename $oldFullPath = Join-Path $archivePath $oldName # 检查原始文件是否存在 if (-not (Test-Path $oldFullPath)) { Write-Warning "文件 $oldName 不存在,跳过" return } # 转换日期格式为 MM-DD-YYYY $date = [DateTime]::Parse($_.date) $dateStr = $date.ToString("MM-dd-yyyy") # 清理主叫姓名和被叫号码中的非法文件名字符 $source = $_.source -replace '[\\/:*?"<>|]', '_' $destination = $_.destination -replace '[\\/:*?"<>|]', '_' # 生成基础新文件名 $newBaseName = "${dateStr}_${source}_${destination}" $ext = [System.IO.Path]::GetExtension($oldName) $newFullPath = Join-Path $archivePath ($newBaseName + $ext) # 处理重名冲突,自动加序号 $index = 1 while (Test-Path $newFullPath) { $newFullPath = Join-Path $archivePath ("${newBaseName}_${index}" + $ext) $index++ } # 执行重命名,可先添加 -WhatIf 参数预览重命名结果 Rename-Item -Path $oldFullPath -Destination $newFullPath -Force }
使用注意事项
- 操作前请先备份全部录音文件,避免误操作导致文件丢失
- 首次执行时可以在
Rename-Item行末尾添加-WhatIf参数,执行后会输出所有重命名操作的预览,确认无误后再删除该参数执行实际重命名 - 代码自动过滤了文件名含
warning:、空大小、主叫/被叫信息为空的无效记录,不会处理这类条目 - 自动替换文件名中的非法字符(如
\ / : * ? " < > |)为下划线,避免Windows文件名不合法报错 - 同一主叫被叫的重复录音会自动加序号后缀(如
06-07-2021_John Doe_5555512345_1.wav),不会覆盖原有文件
内容的提问来源于stack exchange,提问作者user1664305
相关产品推荐
相关产品推荐

