Home > Mobile >  rename files in a folder based on a text file ordering
rename files in a folder based on a text file ordering

Time:08-10

I have a ton of files but they are ordered randomly as they were generated all at the same time.

I have a text file with the names of the files in the correct order. I want to rename the files in the folder to follow the text file like this:

if the file is first on the list in the text file I want to rename it to 1, the second file should be renamed 2.. then 3... etc

I know I can do something like Rename-Item -Path "c:\daily_file.txt" -NewName "monday_file.txt"

but how do I follow the text file ordering

text file looks like this:

car.json
carjkd.json
farmlyar.json
farmlayr2.json

and the folder has these all these files just randomly ordered because they were all created at the same time. the folder has all these files. then i want the file car.json to be named 1 carjkd.json to be renamed 2, farmlyar.json to be renamed 3...etc

CodePudding user response:

If I'm understanding you correctly, you want something like this:

Get-Content -Path "C:\Path\To\file.txt" | 
    ForEach-Object -Begin { [ref]$i = 1 } -Process {
        Get-Item -Path "C:\Path\To\Jsons\$_" | Rename-Item -NewName { "{0}{1}"-f $i.Value  , $_.Extension } -WhatIf
}

This will rename your files that have the same name in your text file in numerical order, starting at 1.


Remove the -WhatIf common/safety parameter when you've dictated those are the results you're after.

  • Related