PowerShell使用-contains查找字符串失败,求问题原因及解决方法
PowerShell中-contains无法匹配字符串子串的原因及解决方法
你遇到的问题核心是对PowerShell的-contains运算符理解有误:
*-contains*是集合包含运算符,用来判断一个集合(比如数组)里是否存在某个完整元素,而非检测单个字符串中是否包含子串。- 你的代码中
$str.ToLower()是单个字符串,此时-contains只会判断该字符串是否与"myappservice"完全相等,显然不满足,所以不会输出"got it"。
正确的解决方法
有三种常用方式可以检测字符串是否包含子串:
- 使用字符串原生的
.Contains()方法
$str = "/microsoft.web/sites/MyAppservice/Instances/1234" if ($str.ToLower().Contains("myappservice")) { write-host "got it" }
- 使用
-like通配符匹配
通过*通配符匹配任意前后内容:
$str = "/microsoft.web/sites/MyAppservice/Instances/1234" if ($str.ToLower() -like "*myappservice*") { write-host "got it" }
- 使用
-match正则表达式匹配
适合需要复杂匹配规则的场景:
$str = "/microsoft.web/sites/MyAppservice/Instances/1234" if ($str.ToLower() -match "myappservice") { write-host "got it" }
内容的提问来源于stack exchange,提问作者Traci
相关产品推荐
相关产品推荐

