Thursday, February 7, 2013

Rename multiple files in a directory / Replace part of a filename in multiple files

Hi All,

This morning I was generating some scripts out of SSMS and it had some wired names attached to it. I wanted to rename them all manually, then it occured that if I write a Powershell script, I could reuse this code for something else in future.. So, here it goes:

Running the script :


[If you get errors, use Set-ExecutionPolicy cmdlet to set the correct permissions]

#Script to remove / rename part of filenames on multiple files..

$a = $args.length

if($a -eq 3)

$workingfolder = $args[0];
$pattern = $args[1];
$replacetext = $args[2];
write-warning "No. or arguments invalid. Usage: "

function Recurse([string]$path) {
$fc = new-object -com scripting.filesystemobject
$folder = $fc.getfolder($path)
foreach ($i in $folder.files) {
$path=$i | select Path
$path = $path -replace "@{Path=",""
$path = $path -replace "}",""
$name=$i | select Name
$name=$name -replace "@{Name=",""
$name=$name -replace "}",""
$name=$name -replace $pattern,$replacetext
Write-Host Renaming $path to $name
#Write-Host $name
Rename-Item $path $name
foreach ($i in $folder.subfolders) {


No comments: