Search code examples
powershellpowershell-2.0rename-item-cmdlet

How to rename files with sequential even and odd numbers in PowerShell?


I would like to know how I can rename the files from a specific folder with a sequence of only even and odds numbers in PowerShell. E.g. Folder1: pag_001.jpg, pag_003.jpg, pag_005.jpg.... pag_201.jpg , Folder2: pag_002.jpg, pag_004.jpg, pag_006.jpg.... pag_200.jpg. It is because I have a document that was scanned first the odds pages and secondly the even pages, therefore their file names are in a consecutive sequence from 1 to 201. Then I separated one half of the files which are the odds pages in a new place: Folder1, and the second half,the even pages in the Folder2. That is why I would like change the names first and the join again together with their new names.

I have tried this based in a similar post:

At the moment I could generate even number sequences like that:

ForEach ($number in 1..100 ) { $number * 2}

and odd numbers like that:

ForEach ($number in 0..100 ) { $number *2+1}

and wanted apply the sequences generated before to rename my files like that:

cd C:\test\Folder1
$i = $number * 2
Get-ChildItem *.jpg | %{Rename-Item $_ -NewName ('pag_{0:D3}.jpg' -f $i++)}

but it doesn't works! Any suggestions are welcome

Regards,


Solution

  • Your $i++ adds 1 each time, this is why it also add even numbers,

    You can create array of Odd Numbers then use the $i++ to step one item in the array, like this:

    $path = "C:\test\Folder1"
    $oddNumbersArray = 0..100 | % {$_ *2 +1}
    $i = 0
    Get-ChildItem $path -Filter *.jpg | % {Rename-Item $_ -NewName ("pag_$($oddNumbersArray[$i]).jpg") ;$i++}
    

    For Even Numbers change the $oddNumbersArray line to {$_ *2}