PowerShell -replace square brackets?

15,993

Solution 1

If you want to include square brackets in a character set put the close square bracket first:

PS C:\> $server1 = '[Serverxyz]'
PS C:\> $server1 -replace '[][]',''
Serverxyz

This works because a character set is [ then one or more characters then ]. So long as you put the ] as the first character in the character set it can't be the terminator and then you can put any other characters you want after it.

Alternatively you can escape the closing square bracket:

PS C:\> $server1 -replace '[[\]]',''
Serverxyz

but the 'traditional' way is to put the square-ket first and avoid the unnecessary escape.

Solution 2

I know it's an old question, but I needed to remove the square brackets and found this:

$server1 = $server1 -replace [regex]::escape('[');
$server1 = $server1 -replace [regex]::escape(']');
$server1

The output will be:

Serverxyz
Share:
15,993
James Brown
Author by

James Brown

Sys Admin at a major telecom company which you've heard of.

Updated on June 16, 2022

Comments

  • James Brown
    James Brown almost 2 years

    So I recently learn that to remove, say, curly braces with -replace, I need to enclose them in square brackets. Like so:

    $server = '{Server123}'
    $server -replace '[{}]',''
    

    So then, my mind wondered, how would we remove square brackets?

    $server1 = '[Serverxyz]'
    

    I've tried escaping with forward slashes, back slashes, using more square brackets, parentheses, curly braces, putting each square bracket into a variable and replacing the variables.

    I'm coming up with nothing. I find a couple of online sources for the procedure, but they are for doing the job in Javascript, or C++, or something besides PowerShell.