Renaming Files In A Directory

So I had a problem on Windows in that I have lots of directories that are named correctly but I wish the files under them to be uniformly named.

The solution was to use PowerShell, which is an extremely effective scripting tool for Windows, especially if you come from a UNIX shell background.

There is actually quite a lot of documentation available for it and rather than go into detail I will simply show you the script:

#
# RenameDirectoryFiles.ps1
#
 
param( [string[]]$paths )
Set-PSDebug -Strict
 
foreach ( $path in $paths ) {
    if ( !(Test-Path $path -PathType Container) ) {
        Write-Error "'$path' doesn't exist or isn't a directory"
        exit 1
    }
 
    $i = 0
    Get-ChildItem $path | sort FullName | foreach {
        $tmp = "{0:000}" -f $i
        $ext = $_.Extension
        $newname = "$path - $tmp$ext"
        Rename-Item $_.fullname $newname
        $newname
        $i = $i + 1
    }
}

So the usage is extremely simple:

RenameDirectoryFiles.ps1 'My Directory'

After which all the files under ‘My Directory’ will be renamed to ‘My Directory – 000.fileextension’.

Leave a Reply

Your email address will not be published.