r/PowerShell • u/kenjitamurako • Feb 28 '26
Question Does anyone know if this behavior is documented? A weird interaction between string interpolation, the sub-expression operator, and a method call if using a string literal with double closing parentheses
I was writing some powershell that updated an ldap query with the replace method and was surprised to find it didn't work despite it being what I'm sure should be the correct syntax.
Here's an example to demonstrate.
This starting ldap query:
$testLdapQuery="(&(wsAccountType=User)(wsIdentity=Yes)(wsMITKerberosID=removethisline))"When you update the query and call replace with a single closing parentheses in the string literal it works as you'd expect but with a malformed result:
# Works as expected with a single closing parentheses but incorrect output
$replacedLdap="$($testLdapQuery.Replace('(wsMITKerberosID=removethisline)',''))(test=test))"The result is imbalanced:
(&(wsAccountType=User)(wsIdentity=Yes))(test=test))
But when you attempt it with a double closing parentheses in the string literal it short circuits the parser and doesn't execute. In fact my linter displays an error:
Missing closing ')' in subexpression.
# Doesn't work
$failedReplaceLdap="$($testLdapQuery.Replace('(wsMITKerberosID=removethisline))',''))(test=test))"It has a simple workaround. Instead of embedding a string literal use a variable in the sub-expression:
# Does work
$ldapReplaceVariable="(wsMITKerberosID=removethisline))"
$successReplaceLdap="$($testLdapQuery.Replace($ldapReplaceVariable,''))(test=test))"Result:
(&(wsAccountType=User)(wsIdentity=Yes)(test=test))
This behavior is the same in powershell 5.1 and 7.5.4. Is this documented anywhere?
I did find some SO posts and bugs on the powershell repository suggesting that subexpressions are generally filled with bugs like this but hadn't seen this specific one reported.
6
u/surfingoldelephant Feb 28 '26
Yeah, it's a parser bug, caused by the uneven number of left parentheses. You can repro it simply with:
The issue disappears when the
(s are balanced. Not that you should do the following, but this works (the commented(balances the number out):See:
1
u/BlackV Feb 28 '26 edited Feb 28 '26
That looks right to me
your replace
.Replace('(wsMITKerberosID=removethisline)','')takes(wsMITKerberosID=removethisline)out leaving you with(&(wsAccountType=User)(wsIdentity=Yes)and)I would personally use the format operator to achieve this and remove the
$()1
u/Over_Dingo Mar 01 '26 edited Mar 01 '26
Seems like parsing logic would need to reset inside interpolated subexressions. That basically adds many passes.