我的文件夹中有几个文件,如下所示:
PM.KDP_client_provide_123_SE.xml
PM.KDP_client_provide_124_SE.xml
PM.KDP_client_provide_125_SE.xml
PM.KDP_client_provide_126_SE.xml
我创建了一个脚本,允许我在PM.KDP_client
之后剪切文件名if ($checkBox2.Checked) {
Try{
Get-ChildItem -path $src |Rename-Item -newname { $($_.BaseName -split '_provide')[0] + $_.Extension};
}catch [System.Exception]{
$listBox1.Items.Add("Error found while processing KDP-files")
}
}
但要避免获得"文件已经存在"错误消息我需要在每个文件名后面的一个向上计数变量。有没有办法实现这个目标?
结果应如下所示:
PM.KDP_client1.xml
PM.KDP_client2.xml
PM.KDP_client3.xml
PM.KDP_client4.xml
答案 0 :(得分:1)
这样的事情应该处理它:
if ($checkBox2.Checked) {
Get-ChildItem -path $src | Group-Object { $_.BaseName -replace '_provide.*$' } | ForEach-Object {
# Note: $_.Name is the constructed value we just grouped on
$name = $_.Name
# Create a counter
$i = 0
try {
# Group is a set of similarly named files
$_.Group | ForEach-Object {
$_ | Rename-Item -NewName "$name$i$($_.Extension)" -ErrorAction Stop
$i++
}
} catch {
$listBox1.Items.Add("Error found while processing KDP-files")
}
}
}