Boucles et conditions PowerShell

De Linuxmemo.

Sommaire

[modifier] Boucles

[modifier] While

while (<condition>)
{
   # bloc d'instruction
}

[modifier] Do-While

do
{
   # bloc d'instruction
}
while (<condition>)

[modifier] For

for (<initial> ; <condition> ; <incrément>)
{
   # bloc d'instruction
}

[modifier] Foreach

foreach (<élément> in <collection>)
{
   # bloc d'instruction
}

[modifier] Structure conditionnelle

[modifier] Conditions operators

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-6

  • Négation
(-Not (test-path fichier))
  • and / or
($a -gt $b) -and (($a -lt 20) -or ($b -lt 20))

[modifier] Conditions Comparison operators

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operator_precedence?view=powershell-6

-eq -ne -gt -gt -lt -le        about_Comparison_Operators
-like -notlike                 about_comparison_operators
-match -notmatch               about_comparison_operators

[modifier] If, Else, Elself

if (condition)
{
   # bloc d'instruction 1
}
else
{
   # bloc d'instruction 2
}
# avec elseif
if (condition)
{
   # bloc d'instruction 1
}
elseif (condition)
{
   # bloc d'instruction 2
}
else
{
   # bloc d'instruction 3
}

[modifier] Switch

switch (<expression>)
{
   <valeur_1> { bloc d'instruction 1}
   <valeur_2> { bloc d'instruction 2}
   <valeur_3> { bloc d'instruction 3}
   <valeur_4> { bloc d'instruction 4}
   Default    { bloc d'instruction 5}
}

[modifier] PowerShell: break, continue, return and exit

  • break -> complete stop of the loop
  • continue -> skip this time but keep going through the loop
  • return -> break and return to calling scope
  • exit -> break EVERYthing including calling scope
Outils personnels