Often you may want to use PowerShell to remove the last N characters from filenames in a particular directory.
You can use the following syntax to do so:
gci | ren -newname {$_.Name.substring(0,$_.BaseName.length-5) + $_.Extension}
This particular example will remove the last 5 characters from each filename in the current directory.
Here is what the various commands do:
- gci: An alias for Get-ChildItem, this retrieves all files in the current directory.
- ren: An alias for Rename-Item, this specifies a new name for each file.
- $_.Name: Retrieves the current filename.
- substring: Specifies that the new filename should be equal to the current filename ranging from index position 0 (the first character) to the full length of the current filename minus 5.
- $_.Extension: Specifies that the original file extension should be added back to the filename.
The following example shows how to use this syntax in practice.
Example: How to Remove Last N Characters from Filenames in PowerShell
First, we can use the gci command (an alias for the Get-ChildItem cmdlet) to first view all filenames in our current directory:

We can see that there are four files in our current directory that all end in the naming convention _data.
Suppose that we would like to remove the last 5 characters from each filename, which will effectively remove _data from the end of each filename.
We can use the following syntax to do so:
gci | ren -newname {$_.Name.substring(0,$_.BaseName.length-5) + $_.Extension}
The following screenshot shows how to use this syntax in practice:

Notice that when we use the gci command again to view all of the files in the current directory we can see that the last 5 characters have been removed from each filename.
Note: Feel free to replace 5 in the code to instead replace a different number of characters from the end of the filenames.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: How to Get File Name from Path
PowerShell: How to Add Date to File Name
PowerShell: How to Delete All Files with Specific Extension
