How do I rename numbered files using powershell?

Nativus N00b 1 Reputation point
2021-04-04T09:25:59.867+00:00

Hello,

I'd like to rename a batch of files with dates, written as follows:

text 2020-12
text 2020-11
text 2020-10
continuing to
text 2016-10

to

2020-12 - text
2020-11 - text

Thanks

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,364 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Andreas Baumgarten 96,361 Reputation points MVP
    2021-04-04T10:32:53.957+00:00

    Hi @Nativus N00b ,

    maybe this is helpful to get started (** Use on your own risk!**):

    ## Remove the -Whatif to execute the renaming ##  
      
    # Rename one file - for instance for testing  
    $file = "Junk/text 2020-12"  
    $fileObj = Get-Item -Path $file  
    $splitName = $fileObj.BaseName.Split(" ")  
    $newName = $splitName[1] + " - " + $splitName[0] + ($fileObj.Extension)  
    $fileObj | Rename-Item -NewName $newName -WhatIf  
      
    # Rename files in folder  
    $folder = "Junk/*"  
    $files = Get-ChildItem -Path $folder -File -Include text*  
    foreach ($obj in $files) {  
        $fileObj = Get-Item -Path $obj  
        $splitName = $fileObj.BaseName.Split(" ")  
        $newName = $splitName[1] + " - " + $splitName[0] + ($fileobj.Extension)  
        $fileObj | Rename-Item -NewName $newName -WhatIf  
        }  
    

    ----------

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

    Regards
    Andreas Baumgarten

    0 comments No comments

  2. Ian Xue (Shanghai Wicresoft Co., Ltd.) 29,651 Reputation points Microsoft Vendor
    2021-04-04T12:47:13.643+00:00

    Hi,

    Please check to see if this works.

    $folder = 'C:\temp\'  
    Get-ChildItem -Path $folder|ForEach-Object{  
        $array = $_.BaseName -split ' '  
        $newname = $array[-1] + ' - '+ ($array[0..($array.count-2)] -join ' ') + $_.Extension  
        Rename-Item -Path $_.FullName -NewName $newname  
    }  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments