PowerShell における論理演算子

  1. PowerShell の論理演算子
  2. PowerShell の -and 演算子
  3. PowerShell の -or 演算子
  4. PowerShell の -xor 演算子
  5. PowerShell の -not 演算子
PowerShell における論理演算子

論理演算子はさまざまな条件を単一の条件に変換することができます。

この記事では、実世界の例を挙げ、PowerShell のスクリプトで論理演算子を適用します。

PowerShell の論理演算子

論理演算子は andorxor、および not または!です。

PowerShell の -and 演算子

出力は、$a$btrue の場合は true、それ以外の場合は false です。

真理値表:

A B 出力
0 0 0
1 0 0
0 1 0
1 1 1
$a = 0
$b = 0
$a -and $b # false (if both variables are false)

$a = 1
$b = 0
$a -and $b  # false (if any of the variables are false)

$a = 1
$b = 1
$a -and $b # true (if both variables are true)

-and 演算子は、両方が true の場合にのみ true を返します。一般に、-and 演算子は、すべての条件がチェックされ、満たされることを望む場合に使用されます。

ここに満たされる必要がある両方の条件の例があります。

$attendance = 102
$paid = "Y"
if ($attendance -gt 100 -and $paid -eq "Y") {
    Write-Output "Allow for examination."
}

出力:

Allow for examination.

PowerShell の -or 演算子

出力は、$a$bfalse の場合は false です。これは -and 演算子と比較しています。

-or 演算子は、出力を true にするために、1つの変数が true であることが必要です。

真理値表:

A B 出力
0 0 0
1 0 1
0 1 1
1 1 1
$a = 0
$b = 0
$a -or $b # false (if both conditions are false)

$a = 1
$b = 0
$a -or $b # true (if any of the variables are true)

$a = 1
$b = 1
$a -or $b  # true (if both of the variables are true)

-or 演算子は、両方の条件が false のときにのみ false を返します。一般に、-or 演算子は、いずれかの条件を true とみなすときに使用されます。

$attendance = 99
$marks = 201
if ($attendance -gt 100 -or $marks -gt 200) {
    Write-Output "Give five extra marks."
}

出力:

Give five extra marks.

PowerShell の -xor 演算子

排他的 or または -xor は、$a または $b のいずれかが true の場合に true を返します。両方の条件が true の場合、-xorfalse の結果を返します。

真理値表:

A B 出力
0 0 0
1 0 1
0 1 1
1 1 0
('a' -eq 'A') -xor ('a' -eq 'z') # true as one of them is true
('a' -eq 'A') -xor ('Z' -eq 'z') # false as both of them is true
('a' -eq 's') -xor ('Z' -eq 'p') # false as both of them are false

PowerShell の -not 演算子

-not 演算子は、式の出力の反対を返します。式の出力が true の場合、演算子はそれを false として返し、その逆も同様です。

-not ('a' -eq 'a') # false as the output of expression is true
-not ('v' -eq 'a') # true as output expression is false
-not ('v' -eq 'V') # false as output expression is true
-not ('V' -eq 'V1') # true as output expression is false

感嘆符!は、-not 演算子と同じです。

!('a' -eq 'a')  # false as the output of expression is true
!('v' -eq 'a') # true as output expression is false
!('v' -eq 'V') # false as output expression is true
!('V' -eq 'V1') # true as output expression is false
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn