Conditional statements
# If/then
if ($x -eq 1)
{
}
else
{
}
#Switch
$x = 1
switch($x)
{
1 {"One"}
"1" {"One - string"}
2 {"Two"; break}
default {"Default"}
}
switch -casesensitive ("Lukasz")
{
"lukasz" {"lysik"}
"Lukasz" {"Lysik"}
}
switch -Wildcard ("Lukasz")
{
"L*" {"Lysik"}
}
Loops
# While
while($x -le 1)
{
}
# Do while
do {
} while($x -le 1)
# Do until
do {
} until($x -eq 1)
# For
for($x=0; $x -lt 10; $x++)
{
}
# Foreach
$numbers = 10,20,30,40
foreach($n in $numbers)
{
}
# Labels with loops
:level1 foreach(...)
{
foreach(...)
{
break level1
# continuer outerloop
}
}
Script blocks
# Assign to variable
$script = {Clear-Host; "Hello World!"}
# Executing
& $script
# Executing script block
& {"Hello World!"}
# Passing parametes to script blocks
$script = {
$x = $args[0]
$y = $args[1]
}
# Executing with parameters
& $script 1 2
# Passing parametes to script blocks (alternative)
$script = {
param($x,$y)
}
# Executing
& $script -x 1 -y 2
# Default values
$script = {
param($x, $y = 1)
}
# Using script block with pipelines
$script = {
begin { Write-Host "Start" }
process {
Write-Host $_
}
end { Write-Host "End" }
}