我在目录中有各种名称,如下所示:
first_file_123456.jpg 5 * second_file_246531 (2).jpg
我要做的是将我的手放在一个 PowerShell 脚本上,该脚本可以获取这些文件并像这样重命名它们:
123456.jpg 246531 (2).jpg
我希望去掉最后一个下划线和所有导致它的文本以重命名我的文件,以便它们可以匹配我的企业资源规划系统中的项目编号。该系统较旧(2004 年技术),因此从那一侧实现自动化已经过时了。
到目前为止,我尝试连接并且似乎无法正常工作的内容如下:
Get-ChildItem -Recurse -filter *_* | `
Foreach-Object {
$oldName = $_.Name
$pos = $oldName.LastIndexOf("_")
$newName = $oldName.Substring($pos + 1)
if (Test-Path $newName) {
# This is where I get lost - if it runs into a duplicate file name
# how can I make the name unique
}
#write-host $_.fullname
write-host $oldName renamed To: $newName | Out-File renamelog.txt
#rename-item $_.FullName -NewName $newName
}
我注释掉了实际执行某些操作以查看输出的命令。