Reputation: 155
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.
Upvotes: 3
Views: 245
Reputation: 17035
Several things you need to know (some are just recommendations):
Rename-Item
via the pipeline, you have to specify the pathRename-Item
, you cannot use a script block for -NewName
+
if the left operand is int
and the right is string
, because it would be interpreted as addition and requires two numbers.-WhatIf
switch on the whole construct, but only individual commands%
(as explained in other answers and comments)-Begin
parameter for initialization*
for Get-ChildItem
is not necessaryHere is the updated code:
Get-ChildItem | foreach -Begin { $c = 1 } -Process {
if ($c % 2) {
$newName = "${c}a.jpg"
}
else {
$newName = "$($c-1)b.jpg"
}
Rename-Item -LiteralPath $_.FullName -NewName $newName -WhatIf
$c++
}
Here is an even shorter version, that pipes directly into Rename-Item
$c = 0
Get-ChildItem |
Rename-Item -NewName {if (++$script:c % 2) {"${c}a.jpg"} else {"$($c-1)b.jpg"}} -WhatIf
Upvotes: 1
Reputation: 61028
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.
Upvotes: 3