PS: Logic Statements And Loops
Description:
This is a collection of PowerShell logic statements and loops.
The If-Then Statement:
-
Setup:
1 2 3 4 5
If (condition) {Do stuff} # Another explanation would be If (test) { "Execute when true" }
-
Example:
1 2 3 4 5 6 7 8 9
$Status=(Get-service -name bits).status If ($Status -eq "Running") { Clear-Host Write-Output "Service is being stopped" Stop-Service -name bits } Else { Clear-Host Write-Output "Service is already stopped" }
The Switch Statement:
-
Setup:
1 2 3 4 5
Switch (pipeline) { Pattern 1 {Statement block} Pattern 2 {Statement block} Pattern n {Statement block} }
-
Example:
1 2 3 4 5 6 7 8
Switch ($status) { 0 { $status_text = 'ok' } 1 { $status_text = 'error' } 2 { $status_text = 'jammed' } 3 { $status_text = 'overheated' } 4 { $status_text = 'empty' } default { $status_text = 'unknown' } }
-
Another Example:
1 2 3 4 5 6 7 8 9
$status = 3 $status_text = switch ($status) { 0 { 'OK' } 1 { 'overheating' } 2 { 'jammed' } 3 { 'empty' } default { 'unknown' } } $status_text
The Do-Until Loop:
-
Setup:
1 2 3 4 5 6 7 8
Do { command_block } until (condition) NOTE: The logic of this loop is to execute the Do {block} until (the condition is true).
-
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13
Clear-Host $strPassword ="123" $strQuit = "Not yet" Do { $Guess = Read-Host "`n Guess the Password" if($Guess -eq $StrPassword) {" Correct guess"; $strQuit ="n"} else{ $strQuit = Read-Host " Wrong `n Do you want another guess? (Y/N)" } } # End of 'Do' Until ($strQuit -eq "N") "`n Ready to do more stuff..."
The Do-While Loop:
-
Setup:
1 2 3 4 5 6 7 8
Do { command_block } while (condition) NOTE: The logic of Do-While is the opposite of the Do Until. {Execute the block statement} while the (condition is true)
-
Example:
1 2 3 4 5 6 7 8 9 10
$a = 1 DO { "Starting Loop $a" $a $a++ "Now `$a is $a" } While ($a -le 5) # Do loop $i= 1
The ForEach Loop:
-
Setup:
1
ForEach (item In collection) {ScriptBlock}
-
Example:
1 2 3 4
$services = Get-Service ForEach ($service in $services) { $service.Displayname }
The For Loop:
-
Setup:
1 2
for (init; condition; repeat) {command_block}
-
Examples:
1 2 3 4
# You can use carriage returns instead of semi-colons: for($i=1; $i -le 10; $i++){ Write-Host $i }
Comments