Windows Powershell條件運算式之條件操作符_PowerShell

來源:互聯網
上載者:User

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解釋引擎將會把條件運算式逐個應用到集合的成員上,結果是包含返回真值的成員新集合。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.