Search code examples
arrayspowershellloopsrename

How to rename file with array pattern new name in PowerShell?


I want to rename a some files. It depends on the array of string new name I have. I tried this, but the files is renaming all. My expectation, the file only rename 3 files, because I only has 3 array. Please help anyone can has idea. Thanks a lot.

$Names = @("Student", "Employee", "Married")

$DataFile = Get-ChildItem -Path .\*.txt #There are more than 10 files

foreach ($name in $Names)
{
     $DataFile | Rename-Item -NewName {"$name" + $_.Name} 
}

Solution

  • For this you will need to created an counter ($i) to index into the other array:

    $Names = 'Student', 'Employee', 'Married'
    $DataFile = Get-ChildItem -Path .\*.txt
    
    $Names | ForEach-Object { $i = 0 } {
        Rename-Item $DataFile[$i] ($_ + $DataFile[$i++].Name)
    }
    

    Note that the ForEach-Object supports multiple script blocks:

    When you provide multiple script blocks to the Process parameter, the first script block is always mapped to the begin block. If there are only two script blocks, the second block is mapped to the process block. If there are three or more script blocks, first script block is always mapped to the begin block, the last block is mapped to the end block, and the blocks in between are all mapped to the process block.

    Related: #13772 Automatic variable for the pipeline index