Search code examples
powershellbatch-rename

Powershell renaming a specific Character


I've been batch renaming .las files in powershell with a simple script:

cd "C:\Users\User\desktop\Folder"
Dir | Rename-Item -NewName {$_.name-replace "-", "" }
Dir | Rename-Item -NewName {$_.name-replace "_", "" }
Dir | Rename-Item -NewName {$_.BaseName+ "0.las"}

This has been working great, but I need to modify it to account for a different naming convention.

The files start out in this format: 123_45-67-890-12W_0 and get converted to 123456789012W00.las

Occasionally the number after the W will be non zero, and I need to carry that on as the last digit, eg. 123_45-67-890-12W_2 needs to go to 123456789012W02

I'm not sure how to use if statements and to select a specific digit in powershell format, which is how I would approach this problem. Does anyone have some ideas on how to go about this?

Thanks


Solution

  • You can use the substring method to get all but the last character in the basename, then concatenate the zero, then use substring again to get the basename's last character, then finish off with the .las extension:

    Dir | Rename-Item -NewName {($_.BaseName).substring(0,$_.BaseName.length - 1) + "0" + ($_.BaseName).substring($_.BaseName.length -1,1) + ".las"}
    #                           ^^^^This gets everything but the last charcter^^^         ^^^^^^^^^^This gets the last character^^^^^^^^^^