Need to omit the leading characters

Khurram Ansari 21 Reputation points
2021-10-08T03:36:54.89+00:00

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
    2021-10-08T06:36:40.877+00:00

    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:

    234809.jpg  
    678380.jpg  
    53900010.jpg  
    539010.jpg  
    

    ----------

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

    Regards
    Andreas Baumgarten


1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 45,831 Reputation points
    2021-10-09T18:12:41.927+00:00

    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 |  
        ForEach-Object{  
            $r = $_.Name -replace '^0+(\d+?\..+)$','$1'  
            if ($_.Name -ne $r){  
                $_ | Rename-Item -NewName $r # rename file  
            }  
        }