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
CodePudding user response:
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") }
CodePudding user response:
If you change the path in the script to where the folders are, the script below changes the name to add a zero before the underscore.
$folderspath = 'C:\Test'
$folders = gci -Path $folderspath
ForEach($folder in $folders) {
$CurrentFolderName = $folder.name
$CurrentFolderName = $CurrentFolderName.tostring()
$NewFolderName = $CurrentFolderName.Replace("_","0_")
$FolderPath = $folder.FullName
Rename-Item -Path $FolderPath -NewName $NewFolderName
}