Control structures are an essential aspect of programming that help you define the logic for decision-making, looping, and managing flow. They enable you to assess conditions and variables to determine actions based on specific scenarios. In this post, we’ll explore key PowerShell control structures and provide code examples to get you started.
Conditional Statements
If / ElseIf / Else
This structure evaluates conditions and executes specific actions based on those conditions.
Syntax:
Switch
switch
to evaluate a variable against multiple values.Syntax:
Using Regular Expressions with Switch
The -Regex
parameter allows regex matching.
$userInput = Read-Host “Enter a value”
switch -Regex ($userInput) {
“^[A-Z]” { Write-Host “User input starts with a letter.” }
“^[0-9]” { Write-Host “User input starts with a number.” }
default { Write-Host “User input doesn’t start with a letter or number.” }
}
Loops and Iterations
ForEach-Object
Processes each item in a collection. Best used when working with piped objects
$path = $env:TEMP + “\baselines”
Get-ChildItem -Path $path | ForEach-Object { Write-Host $_ }
Foreach
While Loop
Executes as long as the condition is true.
Syntax:
while (<condition>) {
<action>
}
For Loop
Defines an initializer, condition, and iteration
Syntax:
for (<init>; <condition>; <iteration>) {
<action>
}
Do-While / Do-Until
Special Statements
Break
Exits a loop immediately.
Example:
Continue
Skips the current iteration and moves to the next one.
Naming Conventions
PowerShell cmdlets and functions follow a Verb-Noun
naming convention, such as Get-Help
or Stop-Process
.
Finding Approved Verbs
Use the Get-Verb
cmdlet to see the list of approved verbs.
This guide provides a comprehensive look at PowerShell control structures and how to leverage them for effective scripting. Practice these examples to enhance your understanding and proficiency!
PowerShell Profiles and Reusability the way towards Fundamentals - Cloud Knowledge
[…] PowerShell host is an application that runs the PowerShell engine (e.g., Windows PowerShell console, PowerShell ISE, […]