Rename Files error which has contain [] in name

I have this script to modify some filename:

$folderPath = "E:\Új mappa"

Get-ChildItem -Path $folderPath -File | ForEach-Object {
    $oldName = $_.Name
    $newName = $oldName.Replace("[", "").Replace("]", "").Replace("(", "").Replace(")", "").Replace("{", "").Replace("}", "").Replace("<", "").Replace(">", "").Replace("\\", "")
    $newPath = Join-Path -Path $folderPath -ChildPath $newName
    Rename-Item -Path $_.FullName -NewName $newName -WhatIf
}

The 3 files to test contain [ ]
. So it only report error which has containinng
[ ]

in their name :
file stucture:
1 [dsadasdasd.txt
2 asd.ps1
3 dsadada[sdf]afsfasdasd.txt

error:

What if: Performing the operation "Rename File" on target "Item: E:\Új mappa\asd.ps1 Destination: E:\Új mappa\asd.ps1".
Rename-Item : Cannot rename because item at 'E:\Új mappa\dsadada[sdf]afsfasdasd.txt' does not exist.
At line:6 char:5
+     Rename-Item -Path $_.FullName -NewName $newName -WhatIf
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand

Rename-Item : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: [dsa
dasdasd.txt
At line:6 char:5
+     Rename-Item -Path $_.FullName -NewName $newName -WhatIf
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Rename-Item], ParameterBindingException
    + FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.RenameItemCommand

Since the characters you want to replace are actually meta characters you have to escape them. Or you use a character class like this:

$oldName = 'Wel[come]Back(To)The{PowerShell}.<org>Fo/rum'
$oldName -replace '[][(){}<>\\/]'

This way you only have to explicitly escape the backslash. :wink:

-Path parameter accepts wildcards, ] and [ are wildcard characters. Therefore, you should use -LiteralPath as it takes that, a literal path (no wildcards)

Get-ChildItem -Path $folderPath -File | ForEach-Object {
    $oldName = $_.Name
    $newName = $oldName.Replace("[", "").Replace("]", "").Replace("(", "").Replace(")", "").Replace("{", "").Replace("}", "").Replace("<", "").Replace(">", "").Replace("\\", "")
    $newPath = Join-Path -Path $folderPath -ChildPath $newName
    Rename-Item -LiteralPath $_.FullName -NewName $newName -WhatIf
}
1 Like

It works only the literalpath, thank you for solution