Windows Powershell条件表达式之条件操作符

Powershell 中的比较运算符
-eq :等于
-ne :不等于
-gt :大于
-ge :大于等于
-lt :小于
-le :小于等于
-contains :包含
-notcontains :不包含

进行比较

可以将比较表达式直接输入进Powershell控制台,然后回车,会自动比较并把比较结果返回。

PS C:Powershell> (3,4,5 ) -contains 2
False
PS C:Powershell> (3,4,5 ) -contains 5
True
PS C:Powershell> (3,4,5 ) -notcontains 6
True
PS C:Powershell> 2 -eq 10
False
PS C:Powershell> "A" -eq "a"
True
PS C:Powershell> "A" -ieq "a"
True
PS C:Powershell> "A" -ceq "a"
False
PS C:Powershell> 1gb -lt 1gb+1
True
PS C:Powershell> 1gb -lt 1gb-1
False

求反

求反运算符为-not 但是像高级语言一样”! “ 也支持求反。

PS C:Powershell> $a= 2 -eq 3
PS C:Powershell> $a
False
PS C:Powershell> -not $a
True
PS C:Powershell> !($a)
True

布尔运算

-and :和
-or :或
-xor :异或
-not :逆

PS C:Powershell> $true -and $true
True
PS C:Powershell> $true -and $false
False
PS C:Powershell> $true -or $true
True
PS C:Powershell> $true -or $false
True
PS C:Powershell> $true -xor $false
True
PS C:Powershell> $true -xor $true
False
PS C:Powershell>  -not  $true
False

比较数组和集合

过滤数组中的元素

PS C:Powershell> 1,2,3,4,3,2,1 -eq 3
3
3
PS C:Powershell> 1,2,3,4,3,2,1 -ne 3
1
2
4
2
1

验证一个数组是否存在特定元素

PS C:Powershell> $help=(man ls)
PS C:Powershell> 1,9,4,5 -contains 9
True
PS C:Powershell> 1,9,4,5 -contains 10
False
PS C:Powershell> 1,9,4,5 -notcontains 10
True

一、值比较

1) -eq: 相等(equal)运算符
2) –ne:不相等(not-equal)运算符
3) –lt: 小于(less-than)
4) –gt: 大于(greater than)
5) le: 小于等于 (less-than-or-equal)
6) ge: 大于等于(greater-than-or-equal)
值比较运算符可以用来比较两个数字,也可以用来比较两个字符串。
注意:字符串比较时忽略大小写,如果需要大小写敏感比较,可以使用操作符-ceq, -clt, -cle, -cge。大小写敏感比较时,小写字母小于大写字母。
在PowerShell中明确的大小写不敏感比较操作符是在默认操作符前加前缀i,即-ieq,-ilt,-ile,-igt,-ige。

二、隐式类型转换

在PowerShell中自动转换的通常规则是对于两个不同类型变量组成的表达式,自动将右侧的变量转换为左侧变量的类型,之后计算表达式的值。

三、逻辑和位操作

1) –and与操作符,在操作符两边的操作数均为$true时返回$true。
2) –or或操作符,在任何一个操作数为$true时返回$true。
3) –xor异或操作符,如果有一个操作数是$true,那么表达式返回$true;如果两个操作数均为$true,则返回$false。
4) –not或者! 取反操作符,只有一个操作数,作用将其取反。
5) –band和-bor按位操作与(-band)和按位或(-bor)操作符,仅用于整数。

四、布尔转换

包括位操作符在内的多个操作符返回数字类型的值,PowerShell可以自动将其转换为布尔类型的值,转换规则是任何非空值将会被转换为$true。非空的概念可以被延伸到更宽泛的范围,下的即PowerShell将会在需要时隐式转换为布尔值。也可以在任何值前加[bool]来显式执行强制类型转换,转换规则如下:
1) 任何非零值将会被转换为$true
2) 非零长度的字符串将会被转换为$true
3) 至少有一项的集合会返回$true
4) 其他对象将会被转换成$true,除非它们为$null

五、-like和-match字符串操作符为真,可以用其检测字符串是否由特定模式组成或其中是否包含所需的字符串形式。

六、集合与条件表达式

PowerShell允许在条件表达式的左边使用集合。Shell解释引擎将会把条件表达式逐个应用到集合的成员上,结果是包含返回真值的成员新集合。