-3

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!

Steven
  • 6,817
  • 1
  • 14
  • 14
Wei Ye
  • 131
  • 4
  • 3
    You can, its called `Rename-Item` and `ForEach` loops. What part of your code are you getting stuck on? Please show your current efforts so we can troubleshoot. – Drew Jun 04 '21 at 02:33
  • Hi Drew, I am not stuck on it, I don't know if I could as I haven't learnt how to use powershell, but as you told me it is feasible, I will go into these “Rename-Item" and "ForEach", thanks. – Wei Ye Jun 04 '21 at 02:40
  • 2
    *Hi Drew, I am not stuck on it, I don't know if I could as I haven't learnt how to use powershell, but as you told me it is feasible, I will go into these “Rename-Item" and "ForEach", thanks* this is a textbook example of what Stack Overflow tries to avoid at questions or as aptly put by the [tour](https://stackoverflow.com/tour), "Don't ask about questions you haven't tried to find an answer for (show your work!)" – Nico Nekoru Jun 04 '21 at 03:12
  • Hi Nico, of course you are correct, but also in my question, I clearly asked "Can I" but not "How". Actually, I searched for this task a while, but I still don't know if it is possible, then I asked. – Wei Ye Jun 07 '21 at 01:47

1 Answers1

1

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.

Steven
  • 6,817
  • 1
  • 14
  • 14