Remove suffix from actual file extension

317 Views Asked by At

I am trying to use Rename-Item to remove trailing characters including the hyphen from a filename, ex. 123456.001.zip-4.22815.ren to 123456-001.zip.

Rename-Item -NewName ($_.Name.split('-')[0])

seems to be something I am missing after the split.

2

There are 2 best solutions below

0
On

The split operation must be performed in a scriptblock ({}). A simple expression (()) won't work.

... | Rename-Item -NewName { $_.Name.Split('-')[0] }

Add -replace '^(\d+)\.', '$1-' if you want the period replaced with a hyphen.

... | Rename-Item -NewName { $_.Name.Split('-')[0] -replace '^(\d+)\.', '$1-' }
0
On

I got my script to work with these changes;

$src = "D:\temp"
Get-ChildItem -path $src -filter *.ren | ForEach-Object {    
 Rename-item -path $_.FullName -newname $_.Name.Split('-')[0]  }