How to loop through files and rename using PowerShell?

后端 未结 2 1415
深忆病人
深忆病人 2020-12-09 16:30

I would like to rename all the jpg files in a folder to uniform convention like Picture00000001.jpg where 00000001 is a counter.

It would be a walk in the park in C

相关标签:
2条回答
  • 2020-12-09 17:00

    Try this to get the FilenameWithOutExtension

    $f.DirectoryName + "\" + $f.BaseName

    0 讨论(0)
  • 2020-12-09 17:08

    You can do this fairly simply in PowerShell:

    ls *.jpg | Foreach -Begin {$i=1} `
       -Process {Rename-Item $_ -NewName ("Picture{0:00000000}.jpg" -f $i++) -whatif}
    

    If you're looking for the "basename" and if you're on PowerShell 2.0 just use the Basename property that PowerShell adds to each FileInfo object:

    ls *.jpg | Format-Table Basename
    

    Note that on PowerShell 1.0, the PowerShell Community Extensions adds this same Basename property.

    If the intent is to append a counter string to the file's basename during the rename operation then try this:

    ls *.jpg | Foreach {$i=1} `
       {Rename-Item $_ -NewName ("$($_.Basename){0:00000000#}.jpg" -f $i++) -whatif}
    
    0 讨论(0)
提交回复
热议问题