Search code examples
variablespowershell-3.0string-literals

POWERSHELL: making a literal string out of a expanded string


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


Solution

  • "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"
    }