Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Rename filename by removing the last few characters

Tags:

powershell

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
RSTUV_2015_10_20

would like to rename them to

ABCDE
HIJKL
MNOPQ
RSTUV

I have tried using the follwing code:

Get-ChildItem 'E:\Thomson Reuters\Stage' | rename-item -newname { [string]($_.name).substring($_.name.length -14) } 

Can anybody tell me where I am going wrong?

like image 301
Sayful Ahmed Avatar asked Oct 21 '15 09:10

Sayful Ahmed


People also ask

How do I rename files in bulk with different names?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

How do I rename multiple files with different names in PowerShell?

Open File Explorer, go to a file folder, select View > Details, select all files, select Home > Rename, enter a file name, and press Enter. In Windows PowerShell, go to a file folder, enter dir | rename-item -NewName {$_.name -replace “My”,”Our”} and press Enter. Using Command Prompt, go to a file folder, enter ren *.

How do you rename a file in PowerShell?

To rename and move an item, use Move-Item . You can't use wildcard characters in the value of the NewName parameter. To specify a name for multiple files, use the Replace operator in a regular expression.


1 Answers

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

like image 181
arco444 Avatar answered Oct 20 '22 00:10

arco444