简体   繁体   中英

Why is the For loop looping the incremented number multiple times?

Alright, so I'm trying to create a script that just renames files within a directory.

Within the Directory there's 2 folders and within each folder there's multiple pictures.

I'm using recurse to go through all of them.

My goal is to rename every single file with the incremented number, but this is not working, instead the script will rename files with the name number (1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,etc)

Anyone able to help with this issue? Any response is appreciated.


What Works:

If I replace what's written inside the script block with:

echo $i

it'll increment with no problem (1, 2, 3, 4, etc)

this does not work:

$targetPath | Rename-Item -NewName {$_.Directory.Name + '_' + $I}

CODE I'M WORKING WITH:

cls

$targetPath = Get-ChildItem -File -path C:\Users\Alban\Pictures\Joshua32GBBackUp -Recurse

$numberOfFiles = Get-ChildItem -File -path C:\Users\Alban\Pictures\Joshua32GBBackUp -Recurse | Measure-Object | % {$_.count}



for($i = 1 ; $i -le $numberOfFiles ; $i++ ) {

  $targetPath | Rename-Item -NewName $i -WhatIf

}

You need to iterate through the files as part of the for loop too, like this:

for($i = 0 ; $i -le $numberOfFiles ; $i++ ) {
   #use indexing to pick the nTh file from the list
  $targetPath[$i] | Rename-Item -NewName $i -WhatIf

}

Note that I dropped your initial setting for $i down to zero, because PowerShell begins indexes at zero.

But I wouldn't do this in production, many people find the logic of a for loop too hard to understand. It would be better to iterate through the files directly and rename them that way instead, like so.

#Set initial value to zero
$i = 0

ForEach ($file in $targetPath){
    $newName = "$($file.BaseName)_$i$($file.Extension)"
    Rename-Item -Path $file -NewName $newName -WhatIf
    $i++
}

To have the files still usable after renaming,

  • keep the extension and possibly a common prefix.
  • As Rename-Item accepts piped input no foreach is neccessary
  • for easier sorting I recommend leading zeroes for the counter

$Counter = 0
Get-ChildItem -File -path C:\Users\Alban\Pictures\Joshua32GBBackUp -Recurse|
    Rename-Item -NewName {'File_{0:D3}{1}' -f $Script:Counter++,$_.Extension} -WhatIf

If the output looks OK, remove the trailing -WhatIf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM