Automatically batch renaming files according to a

2019-07-26 23:15发布

问题:

How can I batch rename files in powershell using the following code:

$nr=1;Get-ChildItem -Filter *.jpg |
  Rename-Item -Newname {"PPPPPPP_{0:d3}.jpg" -f $global:nr++}

where PPPPPPP is the name of parent folder containing these files.

Expected Output :

PPPPPPP_001.jpg
PPPPPPP_002.jpg
PPPPPPP_003.jpg

Files are located in C:\USER\MAIN\BLABLABLA\PPPPPPP folder.

回答1:

  • Get the parent directory's name via $_.Directory.Name inside the script block.

  • Cast the $nr variable to [ref] so that you can modify its value directly in the caller's scope (via .Value), which is preferable to using scope modifier $global: - see below.

$nr = 1
Get-ChildItem -Filter *.jpg | Rename-Item -Newname {
  '{0}_{1:d3}.jpg' -f $_.Directory.Name, ([ref] $nr).Value++
} -WhatIf

-WhatIf previews the renaming operation; remove it, once you're confident that the command will perform as intended.


Optional reading: Modifying the caller's variables in a delay-bind script block or calculated property:

The reason you couldn't just use $nr++ in your script block in order to increment the sequence number directly is:

  • Delay-bind script blocks (such as the one passed to Rename-Item -NewName) and script blocks in calculated properties run in a child scope.

    • Contrast this with script blocks passed to Where-Object and ForEach-Object, which run directly in the caller's scope.
      It is unclear whether that difference in behavior is intentional.
  • Therefore, attempting to modify the caller's variables instead creates a block-local variable that goes out of scope in every iteration, so that the next iteration again sees the original value:

Using a calculated property as an example:

PS> $nr = 1; 1..2 | Select-Object { '#' + $nr++ }

 '#' + $nr++ 
-------------
#1
#1   # !! the *caller's* $nr was NOT incremented 

While you can use a scope modifier such as $global: or $script: to explicitly reference a variable in a parent scope, these are absolute scope references that may not work as intended: Case in point: if you move your code into a script, $global:nr no longer refers to the variable created with $nr = 1.

Quick aside: Creating global variables should generally be avoided, given that they linger in the current session, even after a script exits.

The robust approach is to use a Get-Variable -Scope 1 call to robustly refer to the immediate parent scope:

PS> $nr = 1; 1..2 | Select-Object { '#' + (Get-Variable -Scope 1 nr).Value++ }

 '#' + (Get-Variable -Scope 1 nr).Value++ 
------------------------------------------
#1
#2  # OK - $nr in the caller's scope was incremented

While this technique is robust, it is also cumbersome and verbose.

But you could improve the efficiency as follows:
$nr = 1; $nrVar = Get-Variable nr; 1..2 | Select-Object { '#' + $nrVar.Value++ }

Using the [ref] type offers a more concise alternative, though the solution is a bit obscure:

PS> $nr = 1; 1..2 | Select-Object { '#' + ([ref] $nr).Value++ }

 '#' + ([ref] $nr).Value++ 
---------------------------
#1
#2  # OK - $nr in the caller's scope was incremented

Casting a variable to [ref] returns an object whose .Value property can access - and modify - that variable's value. Note that since $nr isn't being assigned to at that point, it is indeed the caller's $nr variable that is referenced.



回答2:

EDIT: modified due to mklement0s hint.
To get the parent name, use .Directory.Name as another parameter for the format operator

$nr=1
Get-ChildItem *.jpg -file|
  Rename-Item -Newname {"{0}_{1:d3}.jpg" -f $_.Directory.Name,([ref]$nr).Value++} -whatIf

If the output looks OK remove the -WhatIf

This will only work while there are no overlapping ranges doing the rename, in that case you should probaply use a temporary extension.

Sample output on my German locale Windows

WhatIf: Ausführen des Vorgangs "Datei umbenennen" für das Ziel "Element: A:\test\150.jpg Ziel: A:\test\test_007.jpg".
WhatIf: Ausführen des Vorgangs "Datei umbenennen" für das Ziel "Element: A:\test\151.jpg Ziel: A:\test\test_008.jpg".
WhatIf: Ausführen des Vorgangs "Datei umbenennen" für das Ziel "Element: A:\test\152.jpg Ziel: A:\test\test_009.jpg".
WhatIf: Ausführen des Vorgangs "Datei umbenennen" für das Ziel "Element: A:\test\153.jpg Ziel: A:\test\test_010.jpg".
WhatIf: Ausführen des Vorgangs "Datei umbenennen" für das Ziel "Element: A:\test\154.jpg Ziel: A:\test\test_011.jpg".
WhatIf: Ausführen des Vorgangs "Datei umbenennen" für das Ziel "Element: A:\test\155.jpg Ziel: A:\test\test_012.jpg".


回答3:

Another, slightly different way:

$nr=1;Get-ChildItem -Filter *.jpg |
Rename-Item -Newname {"$(split-path -leaf $_.Directory)_{0:d3}.jpg" -f
$global:nr++}