powershellformattingrename-item-cmdlet

Powershell: Format numbers in filenames using Rename-item?


I am trying to rename files that are in sequence. The new file name will include a variable that distinguishes it. How to I format that variable so that it is always 2 digits?

Get-ChildItem *.jpg | %{$x=1} {Rename-Item $_ -NewName "FileName$x.jpg'; $x++}

This is the line I bastardized from multiple sources to try and get it done, but whenever I try to format the variable, I keep running into errors.

I am new to powershell.


Solution

  • And the rename-item saga continues. Expressions as command arguments need '( )' around them.

    Get-ChildItem *.jpg | 
      %{$x=1} {Rename-Item $_ -NewName ('FileName{0:d2}.jpg' -f $x++) -whatif } 
    

    With -f, '0' is the first item, then '1', etc.

    '{0} - {1} - {2}' -f 1,2,3
    

    You would need '$( )' for multiple statements:

    Get-ChildItem *.jpg | 
      %{$x=1} {Rename-Item $_ -NewName $('FileName{0:d2}.jpg' -f $x; $x++) }