0

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.

  • 1
    take a look at the `-f` string format operator. it allows you to tell PoSh to use a certain number of digits. this >>> `'{0:D2}' -f 1` <<< will give you this >>> `01` << – Lee_Dailey Oct 15 '19 at 02:08
  • i've tried that and I dont know where to put the -f. I've tried `Get-ChildItem *.jpg | %{$x=1} {Rename-Item $_ -NewName 'FileName{:d2}.jpg' -f $x; $x++}` But all it did was create an error in the Rename-Item function – TheCandyman Oct 15 '19 at 02:21
  • i see that js2010 showed how to use it ... glad to know that you got it working as needed! [*grin*] – Lee_Dailey Oct 15 '19 at 05:47

1 Answers1

1

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++) }
js2010
  • 23,033
  • 6
  • 64
  • 66