Search code examples
powershellfile-rename

How to use powershell to rename batch files?


I have a lot of files in a folder: aa001.txt aa002.txt ... I want to rename them to: bb001.txt bb002.txt ...

Can I use PowerShell to do such renaming? Thanks!


Solution

  • Generally the community wants to see some effort and or research, but this is a pretty simple task with PowerShell, so I'm going to go ahead and answer.

    # Establish test files
    1..20 |
    ForEach-Object{
        New-Item -Path 'c:\temp\06-02-21' -ItemType File -Name ("aa" + $_.ToString("000")+ ".txt")
    }
    
    # Demonstrate renames:
    Get-ChildItem 'c:\temp\06-02-21' | Rename-Item -NewName { $_.Name.Replace('aa', 'bb') }
    

    The rename only takes place in one line. The previous ForEach-Object just establishes test files for me to work with. The Rename simply pipes the output from Get-ChildItem to Rename-Item, a delay bind script block is used as the argument to -NewName parameter. Granted this will depend on the input names and how you want to alter them, but it shows that you can use the incoming data to determine the new name etc.