Jump to content

Powershell script to remove part of a filename


Recommended Posts

Posted

Hi

 

have tried hard with this one but can't seem to get the correct syntax for what I want to do:

 

I have several folders with bmp files and part of the filename is the SIMS admin no. Here is an example of a few files from one of the folders:

 

002538-523D942422.bmp

002551-C1F480B471.bmp

002555-AC48B2A4C7.bmp

 

So I want to end up with the following:

 

002538.bmp

002551.bmp

002555.bmp

 

I have found this which starts to put me in the right direction:

 

gci *.txt | rename-item -newname { [string]($_.name).substring(1) }

 

I know the above will remove the first character or I can increase the .substring(1) with a higher number to remove more characters from the start. But I want to KEEP the characters at the start and I also want to keep the .bmp at the end. I just can't find examples of variations I can use on the substring.

 

Any help would be appreciated.

 

Thanks

 

Mark

Posted

bit messy but

 

gci *.txt | rename-item -newname { [string]($_.name).substring($_.name.length -14) }

 

would remove the last 14 chars from the name (including 4 for the .bmp, leaving the 523D942422 etc.

Posted
foreach ($file in gci *.bmp) {
$fname = ($file.name).split('.')[0]	# item before the '.'
$prefix = $fname.split('-')[0] # item before the '-'
$newname=$prefix + '.bmp'
rename-item $file $newname 
}

Posted

Thanks Jinnantonnixx

 

I did see the split option and wondered how to use it.

 

That did it!

 

 

foreach ($file in gci *.bmp) {
$fname = ($file.name).split('.')[0]	# item before the '.'
$prefix = $fname.split('-')[0] # item before the '-'
$newname=$prefix + '.bmp'
rename-item $file $newname 
}

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...