Advanced renaming directly in Powershell?

16 views
Skip to first unread message

EH

unread,
Nov 25, 2006, 1:08:01 AM11/25/06
to
Let's say I have multiple files in a directory that all start with the same
name, something like:

file.ext
file_1.ext
file_2.ext
etc...

Now, let's say that for each file name we actually have four files, each
with a different extension:

file.ext
file.ex2
file.ex3
file.ex4
file_1.ext
file_1.ex2
file_1.ex3
file_1.ex4
etc...

How could I write a Powershell script that would rename the sets of files,
starting with a number I'd enter. For example, after I enter 12 the files
above would become:

file12.ext
file12.ex2
file12.ex3
file12.ex4
file13.ext
file13.ex2
file13.ex3
file14.ex4
etc...

I know how to do this in VB script or VB.Net, but I was wondering if it was
possible to do it directly in Powershell.

Thanks for the help

/\/\o\/\/ [MVP]

unread,
Nov 25, 2006, 8:29:08 AM11/25/06
to
as you can use a scriptblock in the NewName parameter of rename-item you
rvery flexible in PowerShell :

PoSH>$num = 12
PoSH>ls file*.ex* | rename-item -newname {if($_.name -match '_(\d)'){$num =
$num + $matches[1]};$_.name -replace "file.*\.", "file$num."} -WhatIf

What if: Performing operation "Rename File" on Target "Item:
C:\PowerShell\file.ex2 Destination: C:\PowerShell\file12.ex2".
What if: Performing operation "Rename File" on Target "Item:
C:\PowerShell\file.ext Destination: C:\PowerShell\file12.ext".
What if: Performing operation "Rename File" on Target "Item:
C:\PowerShell\file_1.ex2 Destination: C:\PowerShell\file13.ex2".
What if: Performing operation "Rename File" on Target "Item:
C:\PowerShell\file_1.ext Destination: C:\PowerShell\file13.ext".
What if: Performing operation "Rename File" on Target "Item:
C:\PowerShell\file_2.ext Destination: C:\PowerShell\file14.ext".

Greetings /\/\o\/\/


"EH" <E...@discussions.microsoft.com> wrote in message
news:FD044B4E-7DBE-466F...@microsoft.com...

/\/\o\/\/ [MVP]

unread,
Nov 25, 2006, 11:04:18 AM11/25/06
to
I did some more explaining about this in an entry on my blog .

http://mow001.blogspot.com/2006/11/powershell-advanced-renaming-of-files.html

Greetings /\/\o\/\/

"/\/\o\/\/ [MVP]" <mow...@hotmail.NoSpam> wrote in message
news:6C000C55-FDC6-44B3...@microsoft.com...

EH

unread,
Nov 25, 2006, 4:24:02 PM11/25/06
to
I tried it out and it works great! Thanks!

I also read the blog post and understood most of it, at least enough to make
some modifications to make it work in my exact environment (different
filenames, etc...)

The -Whatif option saved me a lot of headaches!

Thanks again, Powershell rocks!

Emmanuel

Reply all
Reply to author
Forward
0 new messages