YouTip LogoYouTip

Powershell Control Structures

Control structures are the "brain" of a program, determining under what conditions code executes, whether it repeats, and how to gracefully handle errors.\\n\\nAs a modern scripting language, PowerShell provides a complete set of flow control syntax, including:\\n\\n* Conditional statements: `if`, `elseif`, `else`, `switch`\\n* Loop structures: `for`, `foreach`, `while`, `do-while`\\n* Error handling mechanisms: `try`-`catch`-`finally`\\n\\n* * *\\n\\n## I. Conditional Statements\\n\\n### `if` / `elseif` / `else`\\n\\nBasic syntax:\\n\\nif (Condition 1) { # Condition 1Execute if true} elseif (Condition 2) { # Condition 2Execute if true} else { # Other case}\\n#### Example: Check if disk space is insufficient\\n\\n$disk = Get-PSDrive C if ($disk.Free -lt 5GB) { Write-Output "Insufficient disk space!"} elseif ($disk.Free -lt 10GB) { Write-Output "Disk space is low."} else { Write-Output "Disk space is sufficient."}\\n### `switch`\\n\\nWhen there are multiple possible values to evaluate, `switch` is clearer than multiple `if` statements.\\n\\nswitch ($value) { "start" { Write-Output "Start task" } "stop" { Write-Output "Stop task" } "exit" { Write-Output "Exit program" } default { Write-Output "Unknown command" }}\\nSupports pattern matching:\\n\\nswitch -Wildcard ($filename) { "*.txt" { "Text file" } "*.jpg" { "Image file" } default { "Other type" }}\\n\\n* * *\\n\\n## II. Loop Structures\\n\\n### `for` Loop (Classic counting loop)\\n\\nfor ($i = 1; $i -le 5; $i++) { Write-Output "Line $i times"}\\n### `foreach` Loop (Iterate over collections)\\n\\n$names = "Zhang San", "Li Si", "Wang Wu"foreach ($name in $names) { Write-Output "Hello,$name"}\\nYou can also use the `ForEach-Object` pipeline version:\\n\\n$names | ForEach-Object { Write-Output "Hello,$_" }\\n### `while` Loop (Execute while condition is true)\\n\\n$count = 0while ($count -lt 3) { Write-Output "Count:$count" $count++}\\n### `do-while` and `do-until`\\n\\nThe `do` loop will **execute at least once**:\\n\\n$count = 0do { Write-Output "Current value:$count" $count++} while ($count -lt 3)\\n`do-until`: Stops when the condition becomes true\\n\\n$count = 0do { Write-Output "Current value:$count" $count++} until ($count -ge 3)\\n\\n* * *\\n\\n## III. Error Handling: try / catch / finally\\n\\nPowerShell provides a structured exception handling mechanism for catching and responding to runtime errors.\\n\\n### 3.1 Basic Structure\\n\\ntry { # Try running code that may fail}catch { # Execute on error}finally { # Executes regardless of errors (optional)}\\n### Example: Handling division by zero error\\n\\ntry { $result = 10 / 0}catch { Write-Output "Error occurred:$($_.Exception.Message)"}finally { Write-Output "Operation complete"}\\n### Catching specific exception types\\n\\ntry { Get-Content "Non-existent file.txt"}catch [System.IO.FileNotFoundException] { Write-Output "File not found!"}catch { Write-Output "Other error:$($_.Exception.Message)"}Forcing a command to throw an exception \\nBy default, some commands only print errors and do not enter the `catch` block. In this case, you need to add a parameter:\\n\\nRemove-Item "Non-existent file.txt" -ErrorAction Stop\\nOr set the global preference:\\n\\n$ErrorActionPreference = "Stop"\\n\\n* * *\\n\\n## IV. Summary\\n\\n| Control Structure | Function | Applicable Scenarios |\\n| --- | --- | --- |\\n| `if` / `else` | Evaluate one or more conditions | Checking disk, status, etc. |\\n| `switch` | Multi-branch evaluation (value or pattern matching) | Command parsing, categorization |\\n| `for` | Finite iteration | Clear number of loops |\\n| `foreach` | Iterate over arrays or collections | User lists, file lists, etc. |\\n| `while` | Execute while condition is true | Waiting for a state or change |\\n| `do-while` | Execute at least once | Initial validation + retry mechanism |\\n| `try-catch` | Catch runtime errors, prevent script interruption | File operations, network requests, etc. |\\n| `finally` | Cleanup resources, print logs, and other finishing operations | Ensure a block of code always executes |\\n\\n* * *\\n\\n## V. Practice Tasks\\n\\nTask 1: Determine if a number is even or odd\\n\\n$number = 7if ($number % 2 -eq 0) { "Even number"} else { "Odd number"}\\nTask 2: Iterate over an array and print the length of each item\\n\\n$items = "apple", "banana", "cherry"foreach ($item in $items) { "$item length is $($item.Length)"}\\nTask 3: Handle file reading errors\\n\\ntry { Get-Content "D:\\\\not-exist.txt"}catch { "File read failed:" + $_.Exception.Message}
← Powershell PracticePowershell Pipeline Filtering β†’