Powershell如果String.StartsWith()多个字符串
我对 PowerShell 很陌生,如果字符串不以某个字符开头,我正在尝试运行一些代码,但是我无法让它与多个字符一起使用。
这是工作正常的代码。
if (-Not $recdata.StartsWith("1"))
{
//mycode.
}
但我想要的是像这样的多次检查
if (-Not $recdata.StartsWith("1") -Or -Not $recdata.StartsWith("2"))
{
//mycode.
}
但这不起作用,即使 powershell 没有抛出任何错误,它也会破坏整个功能。我尝试了多种方法,但找不到任何解决方案
回答
MundoPeter指出了您方法中的逻辑缺陷--or应该是-and- 而Santiago Squarzon提供了基于正则表达式的-match运算符的替代方案。
让我提供以下 PowerShell 惯用的解决方案,利用 PowerShell 的运算符仅通过在其名称前添加即可提供否定变体的事实not:
$recdata[0] -notin '1', '2' # check 1st char of LHS against RHS array
$recdata -notlike '[12]*' # check LHS against wildcard expression
$recdata -notmatch '^[12]' # check LHS against regex
也可以看看:
-
-in, is-the-LHS-contained-in-the-RHS-collection 算子 -
-like,通配符匹配运算符 -
-match,正则表达式匹配运算符