bobwid
bobwid

Reputation: 1

Remove suffix from actual file extension

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.

Upvotes: 0

Views: 316

Answers (2)

bobwid
bobwid

Reputation: 1

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]  }

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

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-' }

Upvotes: 2

Related Questions