You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell使用-contains查找字符串失败,求问题原因及解决方法

PowerShell中-contains无法匹配字符串子串的原因及解决方法

你遇到的问题核心是对PowerShell的-contains运算符理解有误:

  • *-contains*是集合包含运算符,用来判断一个集合(比如数组)里是否存在某个完整元素,而非检测单个字符串中是否包含子串。
  • 你的代码中$str.ToLower()是单个字符串,此时-contains只会判断该字符串是否与"myappservice"完全相等,显然不满足,所以不会输出"got it"。

正确的解决方法

有三种常用方式可以检测字符串是否包含子串:

  1. 使用字符串原生的.Contains()方法
$str = "/microsoft.web/sites/MyAppservice/Instances/1234"
if ($str.ToLower().Contains("myappservice")) 
{
  write-host "got it"
}
  1. 使用-like通配符匹配
    通过*通配符匹配任意前后内容:
$str = "/microsoft.web/sites/MyAppservice/Instances/1234"
if ($str.ToLower() -like "*myappservice*") 
{
  write-host "got it"
}
  1. 使用-match正则表达式匹配
    适合需要复杂匹配规则的场景:
$str = "/microsoft.web/sites/MyAppservice/Instances/1234"
if ($str.ToLower() -match "myappservice") 
{
  write-host "got it"
}

内容的提问来源于stack exchange,提问作者Traci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 11:07:33