Rename files matching a regular expression pattern

Share your PowerShell scripts for Deployment Manager

Rename files matching a regular expression pattern

Postby chirayu » Fri Jan 31, 2014 7:13 pm

To control which will files will be renamed, change $searchRegex and to control the new name given to the file, change $newFileName.

Code: Select all
# rename all files in a sub-folder matching a RegEx pattern

Write-Host "executing renaming script...";

# the current environment that we are deploying to
$environmentName = $RedGateEnvironmentName;

# regular expression used to search for files to be renamed.
# It matches files with names like '<fileName>.<environmentName>.<fileExt>'
$searchRegex = "^(?<fileName>.*)\\.(?<$environmentName>.*)\\.(?<fileExt>.*)$";

# find files in any of the sub-folders that match the given regular expression
$filesToRename = Get-ChildItem -Path . -Recurse | Where-Object {$_.Name -match $searchRegex};

foreach ($file in $filesToRename) {
    $pathOfFileToRename = $file.FullName;
    # run the regular expression again on the file name to break the name into sub-parts specified in the regular expression.
    # It also saves the result in $matches variable
   $file.Name -match $searchRegex;
    # New name for the file
    $newFileName = $matches.fileName + "." + "sql";
    Write-Host "renaming $pathOfFileToRename to $newFileName";
    # do a force rename (will overwrite any existing file with the new name)
    Move-Item $file.FullName (Join-Path $file.Directory $newFileName) -Force;
Chirayu Shishodiya
Software Engineer - Deployment Manager
Red Gate
Posts: 73
Joined: Mon Sep 17, 2012 4:48 pm

Return to Deployment Manager PowerShell Scripts

Who is online

Users browsing this forum: No registered users and 0 guests