Search code examples
powershellvariablesreplacerename-item-cmdlet

powershell rename-item replace with variables incrementing


I'm trying to use the output of a Get-Childitem | Where-Object to rename a group of files but instead of rename with a constant name I want to rename with a group of variables, and I'm use the operator -replace to find where in the string is what I want to change. Example:

nane_01 -> name_23
name_02 -> name_24  they are not with the same final digit

this is the code I'm using for test:

$a = 0
$b = 1
$Na= 2
$Nb= 3
Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname { $_.name  -replace "_{0}{1}","_{2}{3}" -f $a++,$b++,$Na++,$Nb++ } -Whatif

I can't find how to make incremental variable work with the -replace operator


Solution

    1. Specify the scope of variables explicitly, otherwise a local copy would be discarded on each invocation of the rename scriptblock.

    2. Search/replace string of -replace operator are separate parameters, so format them separately using parentheses around each one (otherwise PowerShell will try to apply -f to $_.name).

    $script:a = 0
    $script:b = 1
    $script:Na= 2
    $script:Nb= 3
    
    Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname {
        $_.name -replace ("_{0}{1}" -f $script:a++,$script:b++),
                         ("_{0}{1}" -f $script:Na++,$script:Nb++)
    } -Whatif
    

    Or just use one variable:

    $script:n = 0
    
    Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname {
        $_.name -replace ("_{0}{1}" -f $script:n++,$script:n++),
                         ("_{0}{1}" -f $script:n++,$script:n++)
    } -Whatif