Need to omit the leading characters

Khurram Ansari 21 Reputation points

Hi I am very new to PowerShell, and I need to rename multiple files in PS.

I have these file:

1- 000234809.jpg
2- 000678380.jpg
3- 000539010.jpg

I need to rename these files in PowerShell. The new file names should be like this:

1- 234809.jpg
2- 678380.jpg
3- 539010.jpg

Note: I need to remove only first 3 zeros from the file name. Thank you all.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,458 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 103.9K Reputation points MVP

    Hi @Khurram Ansari ,

    please try this to start with the script:

    $filePath = "C:\Junk\1" # get files  
    Get-ChildItem -Path $filePath | ForEach-Object {  
        $b = $_ -replace ('^000', '') # replace leading 000  
        $_ | Rename-Item -NewName { $b } # rename file  

    This is the result:



    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Andreas Baumgarten

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 45,831 Reputation points

    Here's a variation on the answer by @Andreas Baumgarten . This one removes the zeros without regard for how many of them there are. In other words, it renders the string "000000123" as if it were being displayed as the integer value "123".

    $filePath = "C:\Junk\1" # get files  
    Get-ChildItem -Path $filePath |  
            $r = $_.Name -replace '^0+(\d+?\..+)$','$1'  
            if ($_.Name -ne $r){  
                $_ | Rename-Item -NewName $r # rename file