I want to remove the last 11 characters of multiple files names. For example I have these file names:
ABCDE_2015_10_20
HIJKL_2015_10_20
MNOPQ_2015_10_20
RSTU
Just to add to the response from arco444:
Get-ChildItem 'E:\Thomson Reuters\Stage' -filter *.txt | rename-item -NewName {$_.name.substring(0,$_.BaseName.length-6) + $_.Extension -replace "_"," "}
This would rename all .txt files in the directory, remove the last 6 characters of the file name, replace any remaining underscore in the filename with a space but still retain the file extension.
So assuming these were text files you would see something like this:
ABCDE_2015_10_20.txt
HIJKL_2015_10_20.txt
MNOPQ_2015_10_20.txt
RSTUV_2015_10_20.txt
Become this:
ABCDE 2015.txt
HIJKL 2015.txt
MNOPQ 2015.txt
RSTUV 2015.txt
As you want to split
the file name at the 1st underscore,
.split()
method or -split
operator with the zero based index [0]
.BaseName
and keeping the Extension
Get-ChildItem 'E:\Thomson Reuters\Stage' |
Rename-Item -NewName { $_.BaseName.Split('_')[0] + $_.Extension }
You're almost there, you just need to tell substring
exactly where to start and end:
Get-ChildItem 'E:\Thomson Reuters\Stage' | rename-item -newname { $_.name.substring(0,$_.name.length-11) }
By passing two integers to substring
you give it the StartIndex and Length of the string you want to capture. See here for the documentation