Tusvin Iyadoo
Tusvin Iyadoo

Reputation: 13

Powershell Renaming with sequential numeric suffixes

I need some assistance with the below renaming script. I'm trying to rename the below files by adding RAW at the end and with incrementing numbers

Original file names:

AFC17073199C
AFC17080199C
AFC17080299C

File after renaming should be:

AFC17073199CRAW.101
AFC17080199CRAW.102
AFC17080299CRAW.103

Script Used:

cd D:/TempKIG/F.kig_TEMP/E.kig_FILES/F.kig_0829460180

ls

$files = Get-ChildItem -File -Filter '*99C'
$global:i = 0; Get-Random $files -Count $files.Count | 
 Rename-Item -NewName { "$files"+'RAW.{0:100}' -f ++$global:i}

SET resexe=0

Upvotes: 1

Views: 1202

Answers (1)

BenH
BenH

Reputation: 10044

I believe your issue is that you need to loop over the files. Either with ForEach or ForEach-Object. Then you can pipe the individual files to be renamed into Rename-Item

$i = 1
Get-ChildItem D:/TempKIG/F.kig_TEMP/E.kig_FILES/F.kig_0829460180 -File -Filter '*99C' |
    ForEach-Object {
        $_ | Rename-Item -NewName { "$($_.basename)RAW.{0:100}" -f $i}
        $i++
    }

Also no need to put the $i into the global scope. If you want to randomize the order you can pipe Get-ChildItem into Sort-Object {Get-Random} before piping into the ForEach-Object.

If you are running PowerShell on Windows, SET resexe=0 probably isn't doing what you want it to do. This sets the variable ${resexe=0} = $null. If you want to use Set (which is an alias to Set-Variable) you probably would want to use set resexe 0. But $resexe = 0 is much more succinct.

Upvotes: 1

Related Questions