Garrett
Garrett

Reputation: 649

Powershell replace filenames

I am using the same logic i use for renaming but having difficulty getting this to work, are the failures to work due to the naming convention?

Example file: filename.xxxx.xx_xxx (2).jpg

Expected results: filename.xxxx.xx_xxx.jpg

Here's what I have:

$toRename = Get-ChildItem ".\files" 

    foreach($x in $toRename){
    $x | Rename-Item -NewName { $_.Name -replace " (2)", "" }
    }

I added a -WhatIf and the filename simply doesn't change. I must be missing something obvious but I cannot figure it out.

Thanks all

Upvotes: 0

Views: 68

Answers (2)

Santiago Squarzon
Santiago Squarzon

Reputation: 61293

You need to escape the parenthesis, they are a special character.

foreach($x in $toRename)
{
    Rename-Item -Path $x.FullName -NewName ($x.Name -replace "\s\(2\)")
}

Upvotes: 1

Damien
Damien

Reputation: 156

You cannot use $_ in your foreach but $x.

  1. Use "foreach"
$toRename = Get-ChildItem ".\files"
foreach($x in $toRename){
    $x | Rename-Item -NewName { $x.Name.Replace(" (2)", "") }
}
  1. Use ForEach-Object
Get-ChildItem ".\files"  | ForEach-Object { Rename-Item -Path $_ -NewName $_.Name.Replace(" (2)", "") }

Upvotes: 1

Related Questions