Search code examples
powershellforeachsplitget-childitemrename-item-cmdlet

Powershell, Rename a directory after parsing and switching strings of its name


So I am trying to rename several level1-subfolders from something like "xy_1234" to "1234_xy". So far I've achieved to split the strings into variables, build the new directory-name and rename the directory, but I'm completely failing, when trying to automate the process within a for-loop. Please help.

Get-Item $Path | ForEach ( $a, $b = $Path.split('_') | Rename-Item -NewName { $b + ('_') + $a})

Solution

  • I think several subfolders should be caught with a GCI
    taking the "xy_1234" to "1234_xy" literal:

    Get-ChildItem $Path -Dir | Where-Object Name -match '^([a-z]+)_(\d+)$' |
        Rename-Item -NewName {$_.Name.Split('_')[1,0] -join ('_')} -WhatIf