I have a PowerShell code that renaming the files name, and just cutting some letters from the end of the file name. Now I am trying to rename it like this: For example my file name is "a_b_c_d_e_f.txt", so I want to change it to "a_b_c.txt". Any Ideas?
Get-ChildItem 'C:\Users\xxx\Projects\testfiles' -filter *.txt |
Rename-Item -NewName {$_.name.substring(0,$_.BaseName.length-9) + $_.Extension}
To complement Paolo's helpful
-splitanswer with a PowerShell (Core) 7+ solution, where the-splitoperator now accepts negative indices, for splitting from the end of a string:The
-WhatIfcommon parameter in the command above previews the operation. Remove-WhatIfand re-execute once you're sure the operation will do what you want.-split'_', -4splits the input file name into substrings by separator_, extracting up to 4 tokens from the end of the string, and returning whatever remains at the front of the input string as the first element.'a_b_c_d_e_f'is split into prefix'a_b_c'and token array@('d', 'e', 'f')(which we're not interested in here).+ $_.Extensionappends the existing extension to the resulting name, resulting in'a_b_c.txt'Note:
File names that contain no
_instances are left as-is (no renaming occurs).File names with only 1 to 2
_instances are renamed to the prefix before their first_; e.g.'a_b_c.txt'becomes'a.txt'-replace-based solution or modify the-Filterargument to rule out names with fewer than 3_Individual rename operations may fail, if the new, shortened names result in duplicates.