I'm trying to change the names of 561 images using powershell. The first and second changes met my expectations, but when I tried to undo the second change a third time, the results did not meet my expectations.
here is my code:
PS E:\PART_5> $a = 1
PS E:\PART_5> Get-ChildItem | ForEach-Object {
>> $name = "newName_$a" + $_.Extension
>> Rename-Item -Path $_.FullName -NewName $name
>> $a = $a + 1
>> }
PS E:\PART_5> $a = 1
PS E:\PART_5> Get-ChildItem | ForEach-Object {
>> $name = "newestName_$a" + $_.Extension
>> Rename-Item -Path $_.FullName -NewName $name
>> $a = $a + 1
>> }
PS E:\PART_5> $a = 1
PS E:\PART_5> Get-ChildItem | ForEach-Object {
>> $name = "newName_$a" + $_.Extension
>> Rename-Item -Path $_.FullName -NewName $name
>> $a = $a + 1
>> }
and results:
First execution result | Second execution result | Third execution result |
---|---|---|
newName_1.jpg | newestName_1.jpg | newName_1000.jpg |
newName_2.jpg | newestName_2.jpg | newName_1001.jpg |
... | ... | ... |
newName_561.jpg | newestName_561.jpg | newName_1560.jpg |
To test I output the variable "a" in the process and the most amazing thing happened.
PS E:\PART_5> $a = 1
PS E:\PART_5> Get-ChildItem | ForEach-Object {
>> $name = "newestName_$a" + $_.Extension
>> Rename-Item -Path $_.FullName -NewName $name
>> $a
>> $a = $a + 1
>> }
PS E:\PART_5> $a = 1
PS E:\PART_5> Get-ChildItem | ForEach-Object {
>> $name = "newName_$a" + $_.Extension
>> Rename-Item -Path $_.FullName -NewName $name
>> $a
>> $a = $a + 1
>> }
When I loop through these two pieces of code, I find that "newestName" is always correct, looping "a" from 1 to 561; and "newName" is always wrong, and looping from 1 to 1560.
I don't know what the problem is and I hope someone can tell me.
$a = 1000
before the third loop? It's also quite strange that you have 561 files during the first 4 attempts and then suddenly 1561 files in the last attempt... Can you doGet-ChildItem E:\PART_5 |Measure
to test how many files/subfolders you actually have in the directory?(Get-ChildItem)
so the command will finish collecting file and foldernames before it enters the loop.