Wednesday, 9 April 2025

Sample flow

$files = Get-ChildItem -File | Where-Object { $_.Name -match "PARS_Rpt110_" }

foreach ($file in $files) {
    $baseName = $file.Name.Substring($file.Name.IndexOf("PARS_Rpt110_"))
    $newName = $baseName
    $counter = 1

    while (Test-Path -LiteralPath (Join-Path $file.DirectoryName $newName)) {
        $nameOnly = [System.IO.Path]::GetFileNameWithoutExtension($baseName)
        $ext = $file.Extension
        $newName = "$nameOnly ($counter)$ext"
        $counter++
    }

    Rename-Item -Path $file.FullName -NewName $newName
}