Shaya
Shaya

Reputation: 2932

Find files in all child folders, then rename all to increment filenumber

It seems like an easy task though I can't get it to work. I got many jpg files, all named 1.jpg, stored in about 700 child folders. Where is my error?

My code:

$int = 1
Get-ChildItem -Filter "*'1'*" -Recurse | Rename-Item -NewName {$_.name -replace '1', $int++ }

Thanks!

Upvotes: 0

Views: 154

Answers (1)

Matt
Matt

Reputation: 46710

What about something like this:

$int = 2
Get-ChildItem -Filter 1.jpg -Recurse | 
    Rename-Item -NewName {$_.name -replace '1', $int++}

Concerning $int = 2. You need to start one number higher since the first file you would fine would try to rename 1.jpg to 1.jpg. $int++ would increase the number after is was used in the substitution for -replace.

Have to find the documentation to back this up but part of your issue might have been using a scriptblock {} when a subexpression () would have worked just fine.

Also since you know the file name I would think the filter should just be "1.jpg" that way you wont get other files you don't want.

About -Path with Get-ChildItem

You do not need to specify it at all as it will use the current location as it's path. It is good practice to use path so that way you wouldn't accidentally run code against a path you did not mean to. Case and point is you search for the number 1 could easily match files that were not 1.jpg. Renaming all of those could be disastrous ( not really but it could happen. )

Upvotes: 1

Related Questions