Home Dashboard Directory Help

Parser error when using brackets inside of a subexpression by Kirk Munro



Sign in
to vote
Type: Bug
ID: 789636
Opened: 6/6/2013 7:38:49 AM
Access Restriction: Public
User(s) can reproduce this bug


The scenario is simple. You're dynamically building a filter, and you want to add brackets around the items in the filter. Here are the items:

$filters = @('one','two')

And here's the logic to combine those with brackets and an -and operator:

"($($filters -join ') -and ('))"

If you try to do this in ISE, you get red squiggles due to a parser error. If you try to do this in the native console, PowerShell thinks you're not done and uses line continuance to continue the command. Yet it is a complete, valid command.

This works:
$($filters -join ') -and (')

Yet dropping that inside of double-quotes results in an error due to a parser bug.

Here are the most simplified examples I could come up with that cause this bug to show itself:

"$($filters -join '(')"
"$($filters -join ')')"
Sign in to post a comment.
Sign in to post a workaround.
Posted by David Wyatt on 6/12/2013 at 1:31 PM
When the code is written as you say, I get the same error, but I'm not sure whether it's a PowerShell bug or not. Either way, you can get around it by adding an extra set of braces around your separator string inside the subexpression.

$filters = @('one','two')
"($($filters -join (') -and (')))"
Posted by Kirk Munro on 6/6/2013 at 7:42 AM
To workaround this issue, use an intermediate variable.


$filters = @('one','two')
$joinedFilters = $filters -join ') -and ('
$joinedFilters = $filters -join '('
$joinedFilters = $filters -join ')'