2

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

miken32
  • 42,008
  • 16
  • 111
  • 154
WFS
  • 23
  • 4
  • Specify the scope explicitly: `$script:a` and so on everywhere. – wOxxOm Sep 04 '16 at 23:15
  • this worked as I now don't get erros, but the resulsts of the incrementation don't work, like the variable a=0 and the na is = 0, so they dont change the names. Could you point me what is wrong? Sorry I'm new using Powershell – WFS Sep 04 '16 at 23:29

1 Answers1

2
  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
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Thanks for the quick response, but this code worked only with the first file name, the others keep coming with the same name input for me. – WFS Sep 04 '16 at 23:43
  • Well, of course. You need to enumerate the files in reverse. Or move the result to another folder. – wOxxOm Sep 04 '16 at 23:44
  • Thanks a lot for your help, I'd just made a newbie mistake on my last question, but your help solved my doubts. – WFS Sep 04 '16 at 23:50