Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell file rename syntax

I'm trying to rename all the files in a given directory so that they have the sequential format 001a.jpg, 001b.jpg, 002a.jpg etc.

I have tried:

$c=1
get-childitem * | foreach {
if($c/2=[int]($c/2)){
rename-item -NewName {($c-1) + 'b.jpg'} else rename-item - NewName {$c + 'a.jpg'}}$c++} - whatif

But I am getting "the assignment operator is not valid".

The = in the third line is obviously not supposed to be an assignment operator. I just want to check whether the counter is on an even number. I found -ne for not equal to but PS didn't seem to like the -.

I am not sure about the syntax of the new names but the parser doesn't get that far ATM.

Grateful for any pointers.

Edit: I've just realised the numbers would skip but I can fix that once I understand the problem with what I already have.

like image 930
rchivers Avatar asked Jul 26 '26 07:07

rchivers


1 Answers

As commented, if you do not leave spaces around the -eq or -ne operators, PowerShell will interpret the dash as belonging to the math, so

if($c/2-ne[int]($c/2))

Will fail.

Also, to test if a number is odd, it is probably quicker to do if ($c % 2) or if ($c -band 1).

Use -not to test for even numbers.

like image 191
Theo Avatar answered Jul 29 '26 11:07

Theo