P. Grunder P. Grunder - 3 months ago 9
PowerShell Question

PowerShell renaming multiple files with upcounting variable

I have several files in my folder which look like this:

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


I formed a script which allows me to cut the filenames after 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")
}
}


But to avoid getting "file already exists" error messages i would need a upcounting variable behind each filename. Is there a way to achieve this?

The result should look like this:

PM.KDP_client1.xml
PM.KDP_client2.xml
PM.KDP_client3.xml
PM.KDP_client4.xml

Answer

Something like this should handle it:

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")
        }
    }
}