1
votes

I want to batch rename files in multiple directories (20 directories, in each directory 20 files) and I want to each file get prefix of its folder name.

I can do this for single directory with this code:

dir | Rename-Item -NewName {$_.Directory.Name + "_" + $_.Name}

But how to apply this for all folders and files in them?

master folder

  • folder1
    • file1
    • file2
  • folder2
    • file1
    • file2

desired output:

master folder

  • folder1
    • folder1_file1
    • folder1_file2
  • folder2
    • folder2_file1
    • folder2_file2
2

2 Answers

2
votes

I think you can simply add -Recurse to Recurse through the directories (also thanks to @infosecb for pointing out to also add -File switch to only rename files, not directories):

Get-ChildItem * -File -Recurse | Rename-Item -NewName {$_.Directory.Name + "_" + $_.Name}
0
votes

In addition to HAL9256's suggestion, you should include the -File switch in the Get-ChildItem cmdlet to only select files.