Home > Back-end >  Bulk renaming files with sort order through Powershell ignores Sorting
Bulk renaming files with sort order through Powershell ignores Sorting

Time:10-30

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.

CodePudding user response:

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".

CodePudding user response:

Without seeing problematic sample filenames, the most likely problem is the difference in the way Explorer and PowerShell sort strings with numbers.

Screenshot 1

The most reliable way to process files (or folders) in the order displayed in Explorer is to have Explorer supply the list of filenames. This can be done using the propeties and methods of theSS2

Name descending:

SS3

Group order respected as well:

SS4

So, for actual processing, get an ordered list of fully-qualified paths before re-naming, as you don't want to be working with a constantly changing source collection.

$FilePaths = @($WInFolder.ITems()).Path

# Do whatever proceessing you want:

ForEach ($ItemPath in $FilePaths)
{
    ###  Prcess file here
}
  • Related