powershellfile-renamerename-item-cmdlet

Rename-Item does not work without -WhatIf option


I'm facing very weird behavior in Rename-Item cmdlet.

I want to rename a bunch of files, all residing within the same (current) directory. Before renaming, I parse original file names, apply some transformation to them, and finally compose resulting file names invoking Rename-Item command in a loop.

When I add -WhatIf option to Rename-Item, I can see it tells me that running it would rename the files correctly. Also, if I output the resulting filename by printing values of the $newFileName variable before renaming, it is also showing correct new file names.

However, when I remove -WhatIf option and run the script, nothing is actually renamed and no errors or warnings are displayed!

I did some investigation and found that if I remove + $_.Extension from the code, the cmdlet actually renames the files, but they will be without extensions, of course. But I can't figure out why it's not working with extension added?!

Example of the original file name: x 005-Fuji-S-200-CA-6-F81-x 15A RAW.tif.

The goal is to swap first and last parts of the middle part of the file name, so the resulting name is like x x-Fuji-S-200-CA-6-F81-005 15A RAW.tif.

The script (it is always run from the directory where the files reside):

Get-ChildItem -File -Filter '*.tif' -Recurse | 

ForEach {
    
    $baseNameSpaced = $_.BaseName -split ' '
    
    $filmIdArray = $baseNameSpaced[1] -split '-'
    
    $first = $filmIdArray[0]
    $filmIdArray[0] = $filmIdArray[-1]
    $filmIdArray[-1] = $first
    $baseNameSpaced[1] = $filmIdArray -join '-'
        
    $newFileName = $($baseNameSpaced -join ' ') + $_.Extension    
    
    Rename-Item -Path $_.FullName -NewName $newFileName
}

Solution

  • You're modifying the thing you're looping on. Get the complete list of files first. A common practice is to put get-childitem in parentheses so it completes first.

    (Get-ChildItem -File -Filter '*.tif' -Recurse) |