Red Gate forums :: View topic - Rename files matching a regular expression pattern
Return to www.red-gate.com RSS Feed Available

Search  | Usergroups |  Profile |  Messages |  Log in  Register 
Go to product documentation

Deployment Manager PowerShell Scripts forum

Rename files matching a regular expression pattern

Search in Deployment Manager PowerShell Scripts forum
Post new topic   Reply to topic
Jump to:  
Author Message
chirayu



Joined: 17 Sep 2012
Posts: 62

PostPosted: Fri Jan 31, 2014 8:13 pm    Post subject: Rename files matching a regular expression pattern Reply with quote

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

Code:
# 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
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic All times are GMT + 1 Hour
Page 1 of 1

 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group