PowerShell
Logika warunkowa
Szukaj…
Składnia
- if (wyrażenie) {}
- if (wyrażenie) {} else {}
- if (wyrażenie) {} elseif (wyrażenie) {}
- if (wyrażenie) {} elseif (wyrażenie) {} else {}
Uwagi
Zobacz także Operatory porównania , których można używać w wyrażeniach warunkowych.
jeśli, jeszcze i jeszcze jeśli
Program Powershell obsługuje standardowe operatory logiczne warunkowe, podobnie jak wiele języków programowania. Umożliwiają one uruchamianie niektórych funkcji lub poleceń w określonych okolicznościach.
Za pomocą if polecenia w nawiasach ( {} ) są wykonywane tylko wtedy, gdy spełnione są warunki wewnątrz if ( () )
$test = "test"
if ($test -eq "test"){
Write-Host "if condition met"
}
Możesz także zrobić coś else . W tym przypadku wykonywane są else polecenia, if warunki if nie są spełnione:
$test = "test"
if ($test -eq "test2"){
Write-Host "if condition met"
}
else{
Write-Host "if condition not met"
}
lub elseif . Komenda else if uruchamia polecenia, if warunki if nie są spełnione, a warunki elseif są spełnione:
$test = "test"
if ($test -eq "test2"){
Write-Host "if condition met"
}
elseif ($test -eq "test"){
Write-Host "ifelse condition met"
}
Zwróć uwagę na powyższe użycie -eq (równość) CmdLet, a nie = == jak wiele innych języków robi dla równości.
Negacja
Możesz zignorować wartość logiczną, tzn. Wprowadź instrukcję if , gdy warunek jest fałszywy, a nie prawdziwy. Można to zrobić za pomocą -Not komandletu
$test = "test"
if (-Not $test -eq "test2"){
Write-Host "if condition not met"
}
Możesz także użyć ! :
$test = "test"
if (!($test -eq "test2")){
Write-Host "if condition not met"
}
istnieje również operator -ne (nie równy):
$test = "test"
if ($test -ne "test2"){
Write-Host "variable test is not equal to 'test2'"
}
Skrót warunkowy
Jeśli chcesz użyć skrótu, możesz użyć logiki warunkowej z następującym skrótem. Tylko ciąg „false” będzie miał wartość true (2.0).
#Done in Powershell 2.0
$boolean = $false;
$string = "false";
$emptyString = "";
If($boolean){
# this does not run because $boolean is false
Write-Host "Shorthand If conditions can be nice, just make sure they are always boolean."
}
If($string){
# This does run because the string is non-zero length
Write-Host "If the variable is not strictly null or Boolean false, it will evaluate to true as it is an object or string with length greater than 0."
}
If($emptyString){
# This does not run because the string is zero-length
Write-Host "Checking empty strings can be useful as well."
}
If($null){
# This does not run because the condition is null
Write-Host "Checking Nulls will not print this statement."
}