Malformed \p{X} character escape in Powershell

Viewed 1380

I have a comparison statement using -match in PS script


$propValue = (Get-ItemProperty "Registry::$($c.Name)" -Name "$($p)")."$($p)"
$productName =  "C:\Program Files (x86)\MyApplication\MyApp"
if ($propValue -match $productName) 
{
      // Do something
}

On execution, the script throws error as Malformed \p{X} character escape in Powershell. What is happening here? How do I fix this?

Thanks.

1 Answers

-match is a regex operator, and \p{X} is a regex escape sequence used to describe unicode blocks.

What happens here is likely that you have a string value like

sometext\p{b8ee6b4b-fefe-4f77-916f-cb8df996599d}

listed in the registry, and so the regex engine will recognize the p{...} sequence and throw an error after determining that b8ee6b4b-fefe-4f77-916f-cb8df996599d is not a valid unicode block descriptor.

Escape the value of $productName before using it as a regex pattern and it'll work as you expect:

if ($propValue -match [regex]::Escape($productName)) 
{
      // Do something
}
Related