0

i want to replace a square bracket in powershell, to change the title.

my code:

if($finaltitlewithouterrors -like  "*`[*`]") {
    $finaltitlewithouterrors=$finaltitlewithouterrors.Replace("[", '')
   }

i tried other schemas but none of them work, like

if($finaltitlewithouterrors -like  "*`[*") {
    $finaltitlewithouterrors=$finaltitlewithouterrors.Replace("`[", '')
   }

i also tried it with

*``[*

i found a similar question (https://stackoverflow.com/questions/54094312/how-do-i-use-square-brackets-in-a-wildcard-pattern-in-powershell-get-childitem#:~:text=Square%20brackets%20can%20be%20used%20as%20a%20wildcard,and%20consequently%20the%20support%20in%20Powershell%20is%20spotty.) but noting of it work.

for example i have a name called:

BatmanTheDarkNight[1].pdf

and the final name should look like:

BatmanTheDarkNight.pdf

or

BatmanTheDarkNight1.pdf
du7ri
  • 67
  • 1
  • 10
  • Change ```"*`[*`]"``` to ```"*``[*``]"``` or ```'`[*`]'``` – Mathias R. Jessen Jun 11 '21 at 10:38
  • Both answers below are going to be helpful. I would recommend, however, that you take some time and read and understand Microsoft's documentation on [Powershell Comparison Operators (including `-replace`)](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.1) and [Regular Expressions](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-7.1). – Jeff Zeitlin Jun 11 '21 at 10:39

2 Answers2

0

You need to escape the square bracket [ ] characters when using -replace. Here is a rough solution using [regex]::Escape

$fileName = "BatmanTheDarkNight[1].pdf"
$newFileName = $fileName -replace [Regex]::Escape("["), "" `
    -replace [Regex]::Escape("]"), ""

$newFileName
BatmanTheDarkNight1.pdf

Note the use of a backtick to chain -replace operations on the next line.

Jelphy
  • 961
  • 2
  • 11
  • 28
0

Just use the regex -replace for this:

$finaltitlewithouterrors = 'BatmanTheDarkNight[1].pdf' -replace '[\[\]]'
# --> BatmanTheDarkNight1.pdf

Regex details:

[\[\]]     Match a single character present in the list below
           A [ character
           A ] character
Theo
  • 57,719
  • 8
  • 24
  • 41