Monday, December 30, 2013

Simple Powershell To Rename Files in a Directory

Note my script examples are primarily for my use and may not be the best examples of how to do something effectively and efficiently. I don't have native scripting skills so I work from other examples and brute force but they get the job done for me. If you have a suggestion on ways to improve something comments are welcome negative or positive; if negative at least mention what can improve the script.


#Declare variable  (Optional)
$SourceDir=”c:\mydir   

cd $SourceDir  (not really necessary if you have the whole path defined in the variable)
foreach ($a in Get-ChildItem $SourceDir -name)   this gets list of each file in the dir to be used for some action
{
Rename-Item $a somethingelse
}



For example to append some type of identifier to all the filenames in a dir you use

#Declare variable  (Optional)
$SourceDir=”c:\mydir   
cd $SourceDir
foreach ($a in Get-ChildItem $SourceDir -name)
{
Rename-item $a myfile_$a
}



If the list of files in the dir where
orange.txt
red.txt
apple.txt

The new names would be
myfile__orange.txt
myfile_red.txt

myfile_apple.txt

No comments:

Post a Comment