How to: Crop filenames with Powershell

Sometimes you would create some scripts to work with files and for example SQL creates backup files and it adds _backup_timestamp so it’s not easy to work with them in a script.

The below script will crop how much characters you want from the back. Simply change the $location (location of files) $extnsion (file extension) and $characterstoremove (number of characters to remove). This will crop the files to the length you need using Powershell.

$location = "C:\test"
$extension = ".bak"
$characterstoremove = -37
$filelist = (get-childitem $location | Where-Object {$_.mode -match "a"} | foreach-object {$_.name})
foreach ($file in $filelist)
{
$len = $file.length
$len = $len+" "+$characterstoremove
$newname = $file.substring(0,$len)
$newname = $newname + $extension
$newfilename = $location+"\"+$file
Rename-Item $newfilename $newname
clear-variable newname, len
}

Leave a Reply

Your email address will not be published. Required fields are marked *