Book Image

Mastering PowerShell Scripting - Fourth Edition

By : Chris Dent
5 (1)
Book Image

Mastering PowerShell Scripting - Fourth Edition

5 (1)
By: Chris Dent

Overview of this book

PowerShell scripts offer a convenient way to automate various tasks, but working with them can be daunting. Mastering PowerShell Scripting takes away the fear and helps you navigate through PowerShell's capabilities.This extensively revised edition includes new chapters on debugging and troubleshooting and creating GUIs (online chapter). Learn the new features of PowerShell 7.1 by working with parameters, objects, and .NET classes from within PowerShell 7.1. This comprehensive guide starts with the basics before moving on to advanced topics, including asynchronous processing, desired state configuration, using more complex scripts and filters, debugging issues, and error-handling techniques. Explore how to efficiently manage substantial amounts of data and interact with other services using PowerShell 7.1. This book will help you to make the most of PowerShell's automation features, using different methods to parse data, manipulate regular expressions, and work with Windows Management Instrumentation (WMI).
Table of Contents (26 chapters)
24
Other Books You May Enjoy
25
Index

Loops, break, and continue

The break keyword can be used to end a loop early. The loop in the following example would continue until the value of $i is 20. break is used to stop the loop when $i reaches 10:

for ($i = 0; $i -lt 20; $i += 2) {
    Write-Host $i 
    if ($i -eq 10) {
        break    # Stop this loop 
    }
}

The break keyword acts on the loop it is nested inside. In the following example, the do loop breaks early—when the variable $i is less than or equal to 2 and variable $k is greater than or equal to 3:

$i = 1 # Initial state for i
do {
    Write-Host "i: $i"
    $k = 1 # Reset k
    while ($k -lt 5) {
        Write-Host "  k: $k"
        $k++ # Increment k
        if ($i -le 2 -and $k -ge 3) {
            break
        }
    }
    $i++ # Increment i
} while ($i -le 3)

The output of the loop is:

i: 1
  k: 1
  k: 2
i: 2
  k: 1
  k: 2
i: 3
  k: 1
  k: 2
  k: 3
  k: 4

The continue keyword may be used to move on to...