1

I have a string that I build from a couple sources to do matching with later, the short of my code so far is:

$temp = "some\good"
if("some text" -match $temp)

My representation of $temp is simple but actually it is built, this is an example of how it can get built, so no, in this case changing " for ' to pass a literal to $temp won't work. If I hard code the if to use a literal string version of $temp, it works so its a matter of converting the value in $temp to a literal string.

I get the following error when I run my code: parsing "some\good" - Unrecognized escape sequence \g. At [not important] + if($temp2 -match $temp) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], ArgumentException + FullyQualifiedErrorId : System.ArgumentException

1 Answer 1

1

"Converting to literal string" won't help you here. String is a string, it only matters how it's being used, i.e. if the content is being interpreted in some way.

-match operates on regex, and that's it, you can't change that, you'd have to escape every all characters that have a meaning in regex. But you can use select-string instead, which has a switch for simple matching:

$text = "some text"
$patt = "some\good"
if (($text | Select-String -SimpleMatch -Pattern $patt | Measure-Object).count -gt 0) {
    Write-Host "match"
} else {
    Write-Host "nomatch"
}
Sign up to request clarification or add additional context in comments.

1 Comment

i had to check to make the variable i piped in wasn't a $null or empty, otherwise that hit the spot right on, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.