powershellrenamebulk

Bulk renaming files with sort order through Powershell ignores Sorting


Trying to bulk-rename photographs to a given naming scheme while keeping the current sort order with the following code:

Get-ChildItem | ForEach-Object  -begin { $count=1 }  -process { rename-item $_ -NewName "MyNamingSchemeWithIndex-$count.jp2"; $count++ }

The renaming works well, however in some cases, the order gets messed up. I couldn't so far identify any given reason why only some runs are incorrect, expect for the files being jp2 instead of jpeg. With jpeg it so far seems to be right every time.

I tried adding Sort-Object

Get-ChildItem | Sort-Object | ForEach-Object  -begin { $count=1 }  -process { rename-item $_ -NewName "MyNamingSchemeWithIndex-$count.jp2"; $count++ }

But that doesn't seem to help.

Just running

 Get-ChildItem | Sort-Object

Works though and displays proper order.


Solution

  • How's this? Making sure to sort by name. Sort-object also blocks until the whole list is gathered, otherwise I would put (get-childitem) in parentheses, so that it's complete first. Using -whatif to show what would happen, although it's not always true. -verbose would show the real result.

    echo hi | set-content a,b,c
    Get-ChildItem | sort-object name | 
      ForEach-object { $count=1 } { 
      rename-item $_ -NewName MyNamingSchemeWithIndex-$count.jp2 -whatif; $count++ }
    
    What if: Performing the operation "Rename File" on target "Item:
    C:\users\admin\foo\a Destination: 
    C:\users\admin\foo\MyNamingSchemeWithIndex-1.jp2".
    What if: Performing the operation "Rename File" on target "Item:
    C:\users\admin\foo\b Destination: 
    C:\users\admin\foo\MyNamingSchemeWithIndex-2.jp2".
    What if: Performing the operation "Rename File" on target "Item:
    C:\users\admin\foo\c Destination: 
    C:\users\admin\foo\MyNamingSchemeWithIndex-3.jp2".