batch rename using windows powershell

Viewed 58

I am busy with a windows powershell script to batch rename a bunch of folders with IDs, which works perfectly fine. My question is how do i add validation to ensure all the IDs are unique when all my files get renamed. Here is the code:

    param(    
    [Parameter(Mandatory=$true)]
    [int]$idx
)

Get-ChildItem *.sql | Foreach-Object {
 $iPrefix = ('{0:d5}' -f $idx)
 $path = (Split-Path -Path($_))
 $filename = (Split-Path -Path($_) -Leaf) -replace "\[|\]",""
 #%{ write-host $path}
 %{ write-host $filename}
 
 if(!$filename.StartsWith("script","CurrentCultureIgnoreCase"))
 { 
     #%{ write-host "Script$iPrefix - $filename"}
     Rename-Item -LiteralPath(($_)) -NewName("Script$iPrefix - $filename")
     ++$idx
     %{ write-host "Renamed: " + $filename}
 }
}

Here is a screenshot of what i want to avoid: Renamed Folders

As you can see Script02185 is repeated twice, because the script was ran at two different times. How do i ensure that the numbers will remain unique?

1 Answers

Try this.

$files = Get-ChildItem . -Filter *.sql

$prefixedFiles, $unprefixedFiles = $files.Where({ $_.Name -match "^Script\d{5} - " }, 'split')

$usedIDs = [int[]]$prefixedFiles.Name.Substring(6, 5)
$unusedIDs = [System.Collections.Generic.HashSet[int]](1..99999)
$unusedIDs.ExceptWith($usedIDs)

$enumerator = $unusedIDs.GetEnumerator()

$unprefixedFiles | Rename-Item -NewName {

    if (!$enumerator.MoveNext()) { throw "`nThere are no unused IDs." }
    "Script{0:D5} - {1}" -f $enumerator.Current, ($_.Name -replace '\[|\]')

} -ErrorAction Stop -PassThru
Related