Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Escape "*" in -like and -match

When you use -like, escape character to escape “*” depends on quotation marks.

# quotation escape command Result
1 N/A $_ -like “*” Not escaped / Match to any strings
2 ` $_ -like “`*” Not escaped / Match to any strings
3 `` $_ -like “``*” Escaped / Match to ‘*’
4 \ $_ -like “\*” Not escaped / Match to strings start with ‘\’
5 N/A $_ -like ‘*’ Not escaped / Match to any strings
6 ` $_ -like ‘`*’ Escaped / Match to ‘*’
7 `` $_ -like ‘``*’ Not escaped / Match to strings start with ‘`’
8 \ $_ -like ‘*’ Not escaped / Match to strings start with ‘\’

The same goes for -match.

# quotation escape command Result
1 N/A $_ -match “*” Not escaped / Regex compilation error
2 ` $_ -match “`*” Not escaped / Regex compilation error
3 `` $_ -match “``*” ‘*’ works as wildcard / Match to any strings
4 \ $_ -match “\*” Escaped / Match to strings contains ‘*’
5 N/A $_ -match ‘*’ Not escaped / Regex compilation error
6 ` $_ -match ‘`*’ ‘*’ works as wildcard / Match to any strings
7 `` $_ -match ‘``*’ Escaped / Match to strings contains ‘`*’
8 \ $_ -match ‘*’ Escaped / Match to strings contains ‘*’