且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 PowerShell 匹配存储在变量中的字符串

更新时间:2023-02-03 10:00:54

我想说使用通配符之类的操作符,它可以为您省去很多头痛:

I'd say use wilcards and the like operator, it can save you a lot of head aches:

$a -like "$b*"

匹配运算符使用正则表达式模式,并且路径中包含正则表达式特殊字符(转义字符).如果您仍想使用 -match - 请确保对字符串进行转义:

The match operator is using regex pattern and the path is having regex special characters in it (the escape characeter). If you still want to use -match - make sure to escape the string:

$a -match [regex]::escape($b)

这会起作用,但请记住,它可以在字符串的中间匹配,您可以添加^"锚点以告诉正则表达式引擎从字符串的开头进行匹配:

This will work but keep in mind that it can match in the middle of the string, you can add the '^' anchor to tell the regex engine to match from the begining of the string:

$a -match ("^"+[regex]::escape($b))