Renaming files

Overview

I recently had need to work on numerous files in a directory. As a way of keeping tabs on which files I still had to work on, I decided to rename the files (ie a bulk rename) with an extension of ‘.todo’. So the the file:

filename.txt

would become

filename.txt.todo

As I completed work on each file, I would remove the extension ‘.todo’. This enabled me to see which files I had left.

Code

The PowerShell code used could be as follows.

# See how many files we rename.
$counter=0;

# The file extension we're going to rename our files with.
$extension=".todo";

# Move to the directory where the files to be renamed live.
Set-Location C:\temp\tempfiles;

Write-Host "Current working directory is $pwd";

foreach ($oldFilename in Get-ChildItem *.dat)
{
Write-Host "Renaming file $oldFilename";
# $newfilename=$oldFilename + $extension;
$newFilename=[string]::join('', ($oldFilename, $extension));
Move-Item $oldFilename $newFilename;
$counter++;
}

Write-Host "$counter files renamed";

I say could be as there many ways of achieving this aim and this is one approach.

Lines 15 and 16 are alternate ways of putting together our new filename, with line 15 being the easiest way.

See also

MSDN Library documentation String Class

This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a comment