I am new to using PowerShell (and coding for that matter), all I'm trying to do is rename my files).
I have 222 .jpg's that are named
"REF_10001.jpg"
"REF_10002.jpg"
"REF_10003.jpg"
etc
but my problem is that they are in the wrong order, I need to reverse them, for example I need
"REF_10001.jpg" --> "REF_10222.jpg"
and vice versa.
"REF_10222.jpg" --> "REF_10001.jpg"
Is there a way to do this? I have been struggling for hours to rename my files properly, just to realize they are in the wrong order, I am tempted to just go do them individually at this point.
Also if someone could help me to change the files to read
"REF.0001.jpg"
"REF.0002.jpg"
etc.
that would be great.
Or if what I'm asking isn't possible, I have a back up folder of my image sequence before i started trying to rename them, the files read
_0221_Layer 1.jpg
_0220_Layer 2.jpg
...
_0000_Layer 222.jpg
I need to change them so that
"_0221_Layer 1.jpg" --> "Ref.0001.jpg"
...
"_0000_Layer 222.jpg" --> "Ref.0222.jpg"
My assumptions:
So I propose a solution that reverses the first name with the last one, the second with the last before and so on :
A simple method to reverse the order is:
[math]::abs()
function.'^REF_1(\d+)?'
captures () the number without the leading 1."REF.{0:0000}.jpg" -f
is used to create the name inserting the calculated new number with 4 placesIf the output looks OK remove the trailing
-WhatIf
parameter.Sample output last line:
Try this:
It's seems a bit inefficient to me, in that you need to enumerate twice, but it works on my test files, so will hopefully be good enough to resolve your immediate problem.
The first loop adds a unique 'tag' to the filename that is later discarded - this is needed otherwise you end up with clashes (e.g. if you try to name "REF_10001" to "REF_10222", it will fail since the latter already exists.
The following works with a variable number of files and also performs the desired name transformation (in addition to reversing the sequence numbers):
Note: The use of
-WhatIf
previews the command without actually running it. If the preview shows the intended operations, remove-WhatIf
to actually perform it.Note the need to use a
[ref]
-typed aux. variable for the sequence number and to increment it via its.Value
property in the script block ({ ... }
) that calculates the new name, because the script block runs in a different variable scope and therefore cannot directly modify variables in the caller's scope.