Search code examples
powershellbatch-rename

Powershell script to insert a "0" on every folders 3rd position


I already searched through google but cant find an answer.

i want a powershell script to add a zero on every 3rd position on every foldername.

Structure now looks like this:

10_vdvdsfadsgd
11_dsnpdnfp
12_spancfspo
20_ndsknfp
21_mpmsdpfdo

and i want it to be like this:

100_vdvdsfadsgd
110_dsnpdnfp
120_spancfspo
200_ndsknfp
210_mpmsdpfdo

Solution

  • You can rename the folders with Rename-Item, and then insert 0 into the name at a specific index with String.Insert():

    Get-ChildItem path\to\root\folder -Directory |Rename-Item -NewName { $_.Name.Insert(2, "0") }
    

    Using Get-ChildItem's -Filter parameter if you want to target only folders with the given name format:

    Get-ChildItem path\to\root\folder -Directory -Filter "??_*" |Rename-Item -NewName { $_.Name.Insert(2, "0") }