0

I have a string : $row.TableName_Org[$i] The value it contains is

This is a happy little asterisk: '*'

Now I want to do an IF based on the fact that the string contains an asterisk.

    if($row.TableName_Org[$i] -Match "*") {
    //Do Something
    }

However gives me this error:

"*" - Kwantiteitsmeter {x,y} wordt door niets voorafgegaan. parseren       
At C:\Users\hveijer\VS Code Repos\migratie-uitwissel\ReadData.ps1:33 char:4
+    $row.TableName_Org[$i] -match "*"
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException  
    + FullyQualifiedErrorId : System.ArgumentException
1
  • The asterisk is a special charachter for regex. If you want to match some of those charachters you have to escape it ... like this: -match '\*' Commented Mar 24, 2021 at 11:09

2 Answers 2

6

As you've found out yourself, the escape character in PowerShells wildcard/glob mechanism is ` (backtick):

'string with * in it' -like '`*'

... but the backtick is also the escape character for expandable (double-quoted) strings, leading to situations with awkward double escaping, like:

$pattern = "${prefix}``*"

For this reason, I prefer to let PowerShell escape my search terms for me instead of doing it manually:

[wildcardpattern]::Escape("${prefix}*")

For regex patterns (eg. for use with -match), use [regex]::Escape instead:

'string with * in it' -match [regex]::Escape('*')
Sign up to request clarification or add additional context in comments.

2 Comments

It would be nice if you used your suggested wildcardpattern in an example with the original question involving the -Match clause
@ShieldOfSalvation Hereby provided
1

Turns out I had to escape the * using ` (slash backtick)

Comments

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.