James Brown
James Brown

Reputation: 347

PowerShell -replace square brackets?

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.

Upvotes: 5

Views: 20958

Answers (3)

Marco
Marco

Reputation: 1349

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

Upvotes: 1

user2555451
user2555451

Reputation:

The -replace operator works with Regex patterns, where [ and ] have special meaning (they denote a character set). So, you will need to escape the closing bracket ] in the character set:

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

This lets PowerShell know that it is a literal closing bracket and not the end of the character set.

Upvotes: 2

Duncan
Duncan

Reputation: 95622

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.

Upvotes: 6

Related Questions