Rename files matching a regular expression pattern

chirayuchirayu Posts: 79
To control which will files will be renamed, change $searchRegex and to control the new name given to the file, change $newFileName.
# 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
Sign In or Register to comment.