PowerShell
Logica condizionale
Ricerca…
Sintassi
- if (espressione) {}
- if (espressione) {} else {}
- if (espressione) {} elseif (espressione) {}
- if (espressione) {} elseif (espressione) {} else {}
Osservazioni
Vedi anche Operatori di confronto , che possono essere usati in espressioni condizionali.
se, altro e altro se
Powershell supporta gli operatori di logica condizionale standard, proprio come molti linguaggi di programmazione. Ciò consente a determinate funzioni o comandi di essere eseguiti in circostanze particolari.
Con un if i comandi all'interno delle parentesi ( {} ) vengono eseguiti solo se sono soddisfatte le condizioni all'interno di if ( () )
$test = "test"
if ($test -eq "test"){
Write-Host "if condition met"
}
Puoi anche fare un else . Qui i comandi else vengono eseguiti se le condizioni if non sono soddisfatte:
$test = "test"
if ($test -eq "test2"){
Write-Host "if condition met"
}
else{
Write-Host "if condition not met"
}
o un elseif . Un altro se esegue i comandi se le condizioni if non sono soddisfatte e se le condizioni elseif sono soddisfatte:
$test = "test"
if ($test -eq "test2"){
Write-Host "if condition met"
}
elseif ($test -eq "test"){
Write-Host "ifelse condition met"
}
Nota l'uso sopra -eq (uguaglianza) CmdLet e non = o == come fanno molti altri linguaggi per l'equlaità.
Negazione
Potresti voler annullare un valore booleano, cioè inserire un'istruzione if se una condizione è falsa invece che vera. Questo può essere fatto utilizzando la -Not cmdlet
$test = "test"
if (-Not $test -eq "test2"){
Write-Host "if condition not met"
}
Puoi anche usare ! :
$test = "test"
if (!($test -eq "test2")){
Write-Host "if condition not met"
}
c'è anche l'operatore -ne (non uguale):
$test = "test"
if ($test -ne "test2"){
Write-Host "variable test is not equal to 'test2'"
}
Se stenografia condizionale
Se si desidera utilizzare la scorciatoia, è possibile utilizzare la logica condizionale con la seguente stenografia. Solo la stringa 'false' valuterà su 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."
}