Во время чтения файла делайте и готово в powershell

You should know about looping if you want to iterate through items until a condition is met in PowerShell. I will show you how to use the while loop in PowerShell in this tutorial with a few examples.

What is a While Loop in PowerShell?

Syntax of the PowerShell While Loop

The syntax of a while loop in PowerShell is like the below:

while (condition) { # Code block to execute
}
  • condition: This is the expression that is evaluated before each iteration. If it returns true, the loop continues; if it returns false, the loop stops.
  • # Code block to execute: This is the block of code that runs repeatedly as long as the condition is true.

Now, with a few examples, let us see how to work with the while loop in PowerShell.

Read PowerShell Do While Loop

Let us see a few examples of a while loop in PowerShell.

Example 1: Basic While Loop Example

To understand the PowerShell while loop, let us first take a simple example of printing numbers from 1 to 5. Below is the PowerShell script.

$i = 1
while ($i -le 5) { Write-Output $i $i++
}

In this example:

  • We initialize a variable $i with the value 1.
  • The condition $i -le 5 checks if $i is less than or equal to 5.
  • Inside the loop, we print the value of $i and then increment it by 1 using the ++ operator.

You can see the output in the screenshot below after I executed the above PowerShell script using VS code.

powershell while loop

Example 2: While Loop with Array Example

Here is an example of how to use the PowerShell while loop to iterate through an array of strings and print each element.

$fruits = @('Apple', 'Banana', 'Cherry', 'Date', 'Elderberry')
$i = 0
while ($i -lt $fruits.Length) { Write-Output $fruits[$i] $i++
}
  • We define an array $fruits containing a list of fruit names.
  • The condition $i -lt $fruits.Length ensures that the loop runs as long as $i is less than the length of the array.
  • We print each fruit name and increment $i by 1.

I also executed the above script, and you can see the exact required output in the screenshot below:

PowerShell While Loop Examples

Example-3: While Loop With Variables and Operators

In this example, let me show you how to use variables and operators in a PowerShell while loop.

We can use PowerShell Variables, which hold values that change with each iteration, to effectively control the loop’s flow.

Here is an example:

$counter = 0
$maxLimit = 20
while ($counter -lt $maxLimit) { if ($counter % 3 -eq 0) { Write-Output "Counter $counter is divisible by 3" } $counter++
}

This loop uses the $maxLimit variable to determine how many times the loop will iterate. It checks if $counter is divisible by 3 before printing a message.

In the same way, we can use logical operators like -and, -or, and -not to make conditions more flexible.

Here is the complete PowerShell script:

$isRunning = $true
$counter = 0
while ($isRunning -and $counter -lt 10) { Write-Output "Counter is $counter" $counter++ if ($counter -eq 5) { $isRunning = $false }
}

In this example, the loop stops early when $counter reaches 5 because $isRunning is set to false.

Read PowerShell Do-Until Loop Examples

How to Use Break and Continue in While Loop

Let me show you now how to use the break and continue keywords to control how the for loops execute in PowerShell.

Break Statement

The break statement is used to exit the loop prematurely, regardless of the condition. It can be useful when you need to terminate the loop based on a specific condition inside the loop.

Here is an example of how to use the break in a for loop in PowerShell.

$i = 1
while ($i -le 10) { if ($i -eq 5) { break } Write-Output $i $i++
}

In this example:

  • The loop starts with $i initialized to 1 and runs while $i is less than or equal to 10.
  • When $i equals 5, the break statement is executed, terminating the loop.
  • As a result, the loop prints numbers 1 to 4 and then stops.

The screenshot below shows the exact output after I executed the above script.

powershell while loop break

Continue Statement

The continue statement skips the remaining code in the current iteration and moves to the next iteration of the loop. It’s useful to skip certain iterations based on a condition.

Here is an example of how to use the continue statement in a for loop in PowerShell.

$i = 1
while ($i -le 10) { $i++ if ($i % 2 -ne 0) { continue } Write-Output $i
}

In this example:

  • The loop runs while $i is less than or equal to 10.
  • We increment $i at the beginning of each iteration.
  • If $i is an odd number ($i % 2 -ne 0), the continue statement skips the rest of the code in the current iteration.
  • As a result, only even numbers are printed.

You can also look at the screenshot below for the output:

powershell while loop continue

Read Create and Use Functions in PowerShell

How to Use Multiple Conditions in While Loop in PowerShell

In a PowerShell while loop, we can also use multiple conditions. Let me show you how.

In PowerShell, you can use multiple conditions in a while loop by combining them with logical operators such as -and, and -or. The while loop will continue to execute as long as the combined condition is evaluated as true.

Syntax

The basic syntax for a while loop with multiple conditions is:

while (<condition1> -and <condition2> -and <condition3>) { # Code to execute as long as all conditions are true
}
while (<condition1> -or <condition2> -or <condition3>) { # Code to execute as long as at least one condition is true
}

Example

Here’s an example that explains a while loop with multiple conditions using the -and operator. This loop will continue to run as long as both conditions are true:

$counter = 0
$limit = 10
$continue = $true
while ($counter -lt $limit -and $continue) { Write-Output "Counter is $counter" $counter++ # Simulate a condition to exit the loop if ($counter -eq 5) { $continue = $false }
}

In this example:

  • The loop will continue as long as $counter is less than $limit and $continue is $true.
  • Inside the loop, the Write-Output cmdlet prints the current value of $counter.
  • The $counter variable is incremented by 1 in each iteration.
  • When $counter reaches 5, $continue is set to $false, causing the loop to exit after the current iteration.

Here is the output you can see in the screenshot below:

powershell while loop multiple conditions

Read How to Use Multiple Conditions in PowerShell If Else Statement?

Nested While Loop in PowerShell

This is very useful; you should know how to work with nested while loops in PowerShell.

Nested while loops in PowerShell are used when you need to perform iterative operations within another set of iterative operations.

Nested While Loop Syntax

The basic syntax for nested while loop is:

while (<outer condition>) { while (<inner condition>) { # Code to execute in the inner loop } # Code to execute in the outer loop
}

Nested While Loop Example

Here’s an example that shows nested while loops by generating a simple grid of coordinates:

# Initialize outer loop variables
$x = 0
$xLimit = 3
# Outer while loop
while ($x -lt $xLimit) { # Initialize inner loop variables $y = 0 $yLimit = 3 # Inner while loop while ($y -lt $yLimit) { # Display the current coordinates Write-Output "Coordinates: ($x, $y)" # Increment the inner loop variable $y++ } # Increment the outer loop variable $x++
}

In this example:

  • The outer while loop iterates over the x coordinate.
  • The inner while loop iterates over the y coordinate.
  • For each iteration of the inner loop, the current coordinates (x, y) are displayed using Write-Output.
  • The inner loop variable $y is incremented in each iteration of the inner loop.
  • After the inner loop completes, the outer loop variable $x is incremented, and the process repeats until the outer condition is no longer true.

If you execute the above code using VS code, you can see the output in the screenshot below:

Nested While Loop Example PowerShell

Conclusion

I hope you got an idea of how to work with while loop in PowerShell with various examples.

I have also explained how to use break and continue in a PowerShell while loop and how to use multiple conditions in a while loop in PowerShell. I explained how to work with nested for loop in PowerShell at the end using an example.

If you still have any questions, feel free to let us know in the comment box below.

PowerShell Do-While Do-Until Loops

In this article, we will cover everything you need to know about PowerShell “Do while” and “Do until” loops, including their definition, functionality, and applications. We will also show examples of how to use it to enhance the efficiency of your PowerShell scripts. So, let’s get started!

Introduction to PowerShell Do-While and Do-Until Loops

The Do While and Do Until loops are two of the most commonly used while loops in PowerShell. The Do While loop is used when you want to execute a set of instructions until a certain condition is met, while the Do Until loop is used when you want to execute a set of instructions until a certain condition is false.

Understanding the ‘Do While’ Loop in PowerShell

Во время чтения файла делайте и готово в powershell
Do { # Code to be executed
} While (condition)

Here is an example of a simple do-while loop that counts down from 1 to 5:

$i = 1
Do { Write-Output $i $i++
}
While ($i -le 5)

The output of this code will be:

do while in powershell
$counter = 0
do { # Code to be executed within the loop Write-Host "Counter: $counter" # Increment the counter $counter++
} while ($counter -ne 5)

The ‘Do Until’ Loop in PowerShell

The Do Until loop is a variation of the Do While loop found in many other programming languages. The primary difference between the two is that the Do Until loop executes until a specific condition evaluates to True. In contrast, the Do While loop executes as long as a particular condition evaluates to True.

Do { #Code to be executed
} Until (condition)
$counter = 1
Do
{ Write-Host "Counter value: $counter" $counter++
} Until ($counter -gt 5)

In the example above, the Do Until loop continues to run until the counter reaches the value of five. Once the counter equals 5, the condition becomes True, and the loop exits.

:/>  Команда для блокировки экрана на клавиатуре и 7 способов сделать игру во весь экран в Windows
do until in powershell

Here is an example of a Do Until loop in PowerShell that generates random numbers between 1 and 10 continuously until the random number equals 7:

$number = Get-Random -Minimum 1 -Maximum 10
do { Write-Host "Generated: $number" $number = Get-Random -Minimum 1 -Maximum 10
} until ($number -eq 7)
Write-Host "Got lucky number 7!"
Do { [int]$input = Read-Host "Enter a number between 1 and 10"
} Until ($input -gt 0 -and $input -le 10)
Do { Write-host "Waiting for WebClient Service to Start..." Start-Service -Name WebClient Start-Sleep -Seconds 5
} Until ((Get-Service -Name WebClient).Status -eq "Running")

In the above script example, the Do Until loop will continue to execute until the WebClient service is running. The loop will start the service and then wait for five seconds before checking the service status again.

Using Break and Continue in Loops in PowerShell

In PowerShell, you can use the break and continue statements within loops to control the flow of execution.

  • Using the ‘Break’ keyword to exit the loop prematurely, based on a certain condition.
  • Using the ‘Continue’ keyword to skip the current iteration of the loop, based on a certain condition.

Here’s an example of how you can use break and continue in these loop constructs:

# Example with break statement in do-while loop
$count = 1
do { Write-Host "Iteration: $count" if ($count -eq 3) { break # Exit the loop when count equals 3 } $count++
} while ($true)
# Example with continue statement in do-until loop
$count = 1
do { if ($count -eq 2) { $count++ continue # Skip the current iteration when count equals 2 } Write-Host "Iteration: $count" $count++
} until ($count -gt 5)

In the first example, a do-while loop is used with the condition ($true) to create an infinite loop. Within the loop, the value of $count is checked as an exit condition, and when it equals 3, the break statement is encountered, causing the loop to exit.

In the second example, a do-until loop is used with the condition ($count -gt 5) to continue until $count exceeds 5. Inside the loop, the value of $count is checked, and when it equals 2, the continue statement is encountered, skipping the current iteration and proceeding to the next iteration.

The break statement is used to immediately exit the loop, while the continue statement is used to skip the remaining code within the loop for the current iteration and move to the next iteration.

Differences Between ‘Do While’ and ‘Do Until’ Loops in PowerShell

Do-While Loop in PowerShell
# Do Until Loop
Do { [int]$number = Read-Host "Please enter a number > 10"
} Until ($number -gt 10)
# Do While Loop
Do { [int]$number = Read-Host "Please enter a number < 10"
} While ($number -le 10)

Best Practices for Using the ‘Do While’ and ‘Do Until’ Loops in PowerShell

  • Always specify a condition that will eventually become false, to avoid infinite loops. Test the condition thoroughly to ensure that the loop will terminate.
  • Use clear and concise variable names to make your code more readable.
  • Use comments to explain the purpose of your code and any complex logic.

To troubleshoot issues with a Do While loop in PowerShell, you can:

  • Use the Write-Host or Write-Output cmdlets to output diagnostic information within the loop.
  • Use the PowerShell ISE or Visual Studio Code with the PowerShell extension for debugging.
  • Verify that the condition is being evaluated correctly and that the code block is executing as expected.
  • Check for any unintended infinite loops by ensuring that the condition eventually becomes false.

Common Mistakes to Avoid

When using the ‘Do While’ loop in PowerShell, there are some common mistakes that you should avoid. Here are a few common mistakes to watch out for:

  • Forgetting to initialize the loop variable before entering the loop.
  • Forgetting to update the loop variable inside the loop, which can cause an infinite loop.
  • Using a condition that always evaluates to true, which can also cause an infinite loop.

Conclusion

PowerShell’s loops are a powerful tool that can be used to automate processes and tasks. They can be used to iterate over objects and arrays, wait for a certain condition to be met, or monitor services. They can also be used to automate processes, such as logging in to multiple systems or checking for new data. The Do While loop is used when you want to execute a set of instructions until a certain condition is met, while the Do Until loop is used when you want to execute a set of instructions until a certain condition is false.

When using PowerShell while loops, there are a few best practices to keep in mind. Make sure to use the correct syntax, use the correct condition, set the initial value, use the correct type of loop, and use the appropriate methods for troubleshooting. By mastering PowerShell while loops, you can automate processes and tasks and make them much more efficient. With the right knowledge and understanding, you can quickly become an expert in this powerful tool. Here is another post on How to use ForEach Statement and ForEach-Object Loop in PowerShell?

What is a “do while” loop in PowerShell?

What is the PowerShell Do Until loop?

How to Create an Infinite Loop in PowerShell?

How do I loop an array in a PowerShell script?

How do I skip a loop iteration in PowerShell?

How do you break a loop to stop?

What is the difference between do while and while loop in PowerShell?

Can I use multiple conditions in a “do while” loop?

How can the ‘break’ and ‘continue’ commands be used in PowerShell Do Until loops?

For example, in bash the script is

cd tmp &&
inotifywait -me close_write,create,move --format %f *.tmp | while read file
do rclone move "$file" dropbox:
done

What should it be like in Powershell?

I only found that && could be replaced with -and
How about the rest?

mklement0's user avatar

67 gold badges673 silver badges862 bronze badges

asked Oct 2, 2023 at 10:33

God of Money's user avatar

Use the ForEach-Object cmdlet, which processes each input object one by one.

With external programs, it is each output line that constitutes an object, i.e. PowerShell streams the (stdout) output from external programs line by line through its pipeline.

# See info re *.tmp and && below.
inotifywait -me close_write,create,move --format %f *.tmp | ForEach-Object { rclone move $_ dropbox: }
  • In PowerShell, *.tmp only expands to the list of matching file names on Unix-like platforms, which requires use of PowerShell (Core) 7+, the modern, cross-platform edition of PowerShell.

    • On Windows (irrespective of whether you use PowerShell (Core) or the legacy Windows PowerShell edition), no such expansion is performed; replace *.tmp with (Get-Item *.tmp).Name there. (For more control over what gets matched, you can use Get-ChildItem instead of Get-Item).
      • Since this technique also works on Unix-like platforms, you can use it in cross-platform scripts.
  • The automatic $_ variable is used to refer to the input line at hand.


answered Oct 2, 2023 at 12:09

mklement0's user avatar

67 gold badges673 silver badges862 bronze badges

PowerShell scripts have several loop options to make automation easy. Learn the difference between Do-While and Do-Until loops and choose which one works best for you.

As a scripting language, PowerShell provides various loops to help with automation tasks. Understanding Do-Until loops vs. Do-While loops is essential to utilize them effectively.

The Do-Until and Do-While loops only differ syntactically in the keywords they use. Choosing between the two comes down to how you want the loop to evaluate your condition. The Do-Until loop will continue to loop while the condition is false. Do-While will continue to loop while the condition is true. Knowing this will help you write more efficient and straightforward scripts.

Do-Until

In Figure 1, a service is started and then the loop waits for one second before it checks to see if the service’s status is equal to “Running.” If the service is not running, then the loop will run again until the service is running.

Do-Until loop code syntax.
Figure 1. This Do-Until loop repeats until the conditions are true.

Do-While

An example of the Do-While code syntax.
Figure 2. The syntax for Do-While is similar to that of Do-Until.

Figure 2 is similar to the Do-Until example, but it operates differently. In this case, the script will enter the loop, sleep for one second and then check to see if the specified service is running. If it is, it will continue to sleep and only exit the loop when the service stops. This approach is useful if you need to monitor a service.

Comparing to the While loop

Bringing them all together

To illustrate the differences between these three loops, we can combine them all into a simple service monitor script.

An example of all three commands being used in a single script.
All three loops can form a service monitor script.

In the example in Figure 3, the While loop will execute until the script is halted since $true always evaluates to true. The Do-Until loop will wait until the service starts, and the Do-While will wait until it stops. Once the service has stopped, the process will start over again. This is a simple way to run a script that will continually start a service that is stopping.

Anthony Howell is an IT expert who is well-versed in multiple infrastructure and automation technologies, including PowerShell, DevOps, cloud computing, and the Windows and Linux operating systems.

Dig Deeper on IT systems management and monitoring


Related Q&A from Anthony Howell

How to roll back Git code to a previous commit
Manage the Windows PATH environment variable with PowerShell
PowerShell looping examples for the 4 key commands

So, in this comprehensive guide, I will cover everything you need to know about while loops in PowerShell, from understanding the syntax, usage, and practical examples to advanced techniques for combining multiple conditions. By the end of this guide, you will have a solid foundation of While loop fundamentals, understand best practices, and be proficient in creating robust While loops that improve your PowerShell automation.

:/>  Какие программы нужны сразу после установки Windows: 10 самых важных

Table of contents

  • Introduction to PowerShell While Loops
  • Understanding the Syntax of PowerShell While Loops
  • The Different Types of While Loops in PowerShell
  • Using While Loops in PowerShell Scripts
  • Examples of PowerShell While Loops
  • Breaking and Exiting While Loops in PowerShell
  • Using Continue in PowerShell While Loops
  • Combining Multiple Conditions in PowerShell While Loops
  • Best Practices for Using While Loops in PowerShell

Introduction to PowerShell While Loops

while (condition) { # code to execute while condition is true
}

The loop evaluates a Boolean expression as the condition before each iteration. If the condition is true, it executes the code inside the loop. This process continues until the condition is false.

Understanding the Syntax of PowerShell While Loops

powershell while loop

To use while loops effectively in PowerShell, it is important to understand the syntax. The while loop is used when you want to repeat a set of commands until a specific condition is met. The loop continues to run as long as the condition is true, and it stops when the condition becomes false. The condition in a while loop can be any expression that evaluates to a Boolean value, such as a comparison or logical operator.

$i = 1
while ($i -le 10)
{ Write-Host $i $i++
}
PowerShell While

Here is another example of using a while loop to iterate over an array:

$array = @("apple", "banana", "cherry")
$i = 0
while ($i -lt $array.Length) { Write-Host $array[$i] $i++
}

The Different Types of While Loops in PowerShell

While Loop

$val = 0;
while($val -ne 5)
{ $val++ Write-Host $val
}

Do-While Loop

do { # command block
} while (condition)

Here is another post on How to use Do-While and Do-Until Loops in PowerShell?

Using While Loops in PowerShell Scripts

While loops are often used in PowerShell scripts to automate tasks and perform calculations. One common use case for while loops is iterating through a list of items and performing a series of actions on each item.

#Get All Items from a Folder
$Files = Get-ChildItem -Path "C:\Logs"
$i = 0
#Move All files and Folders to a Arhive Location
while ($i -lt $Files.Count) { $File = $Files[$i] $NewLocation = "C:\Archive\$($File.Name)" Move-Item -Path $file.FullName -Destination $NewLocation $i++
}

In this example, the while loop iterates through each file in the $files array and moves it to a new location. The loop continues until all files have been moved.

Examples of PowerShell While Loops

Example 1: Password Generator

$length = 8
$characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"
$i = 0
$password = ''
while ($i -lt $length) { $index = Get-Random -Minimum 0 -Maximum $characters.Length $password += $characters[$index] $i++
}
Write-Host "Your password is: $password"

In this example, the while loop generates a random password of a specified length by iterating through the $characters string and selecting a random character at each iteration.

powershell while loop

Example 2: User input validation

#Set the initial flag value
$ValidInput = $false
while (-not $validInput) { $Input = Read-Host "Enter a valid input (e.g., 'Y' or 'N')" If ($input -eq "Y" -or $input -eq "N") { $validInput = $true } Else { Write-Host -f Yellow "Invalid input. Please try again." }
}
Write-Host -f Green "Valid input received: $input"

Example 3: Fibonacci Sequence

$num1 = 0
$num2 = 1
$count = 0
while ($count -lt 20) { Write-Host $num1 $temp = $num1 + $num2 $num1 = $num2 $num2 = $temp $count++
}

In this example, the while loop generates the first 20 numbers in the Fibonacci sequence by iterating through a series of calculations and storing the result in $num1 and $num2.

Breaking and Exiting While Loops in PowerShell

while (condition)
{ # code to execute if (some condition) { break }
}
$Names = @("John", "Jane", "Mary", "Mark", "Alex")
$SearchName = Read-Host "Enter a name to search for "
$Found = $false
while (-not $found) { foreach ($name in $names) { if ($name -eq $searchName) { $found = $true Write-Host -f Green "Name found: $name" break # Exit the while loop } } if (-not $found) { $searchName = Read-Host "Name not found. Enter a new name to search for " }
}

Using Continue in PowerShell While Loops

The continue keyword is used to skip the current iteration of a while loop and immediately start the next one. When PowerShell encounters the continue keyword inside a while loop, it will skip the current iteration of the loop and immediately start the next iteration of the loop. This can be useful when you need to skip over specific items or conditions in a loop.

while (condition)
{ # code to execute if (some condition) { continue } # more code to execute
}
$numbers = 1..10
$i = 0
while ($i -lt $numbers.Count) { if ($numbers[$i] % 3 -eq 0) { $i++ continue } Write-Host $numbers[$i] $i++
}

In this example, the while loop iterates through each number in the $numbers array and checks if the number is divisible by 3. If the number is divisible by 3, the continue statement skips to the next iteration of the loop.

Combining Multiple Conditions in PowerShell While Loops

while ($condition1 -and $condition2)
{ # code to execute
}

Best Practices for Using While Loops in PowerShell

Initialize the variables

Always initialize the variables you use in the while loop before the loop starts.

Use Clear and Concise Conditions

The condition in a while loop should be clear and concise, making it easy to understand the purpose of the loop. Avoid using complex expressions or multiple conditions, as this can make the code more difficult to read and debug. Ensure that the condition in the While loop evaluates to false eventually.

Limit the Number of Iterations

While loops that execute indefinitely can cause performance issues and even crash your system, whenever possible, limit the number of iterations in your while loops to avoid these issues.

Use Break and Exit Statements

The break and exit statements can be used to terminate a while loop prematurely, regardless of the type of loop. Use these statements whenever possible to reduce the number of unnecessary iterations and improve performance.

Double-check for infinite loops

Test the loop condition carefully to avoid infinite loops that can crash your system.

Conclusion

While loops can run code repeatedly, simplifying complex repetitive operations and allowing for varying degrees of inner processing. Remember to start with the basics, experiment, and ensure that the while loop conditions ultimately evaluate to false. With the skills and knowledge gained from this guide, you can confidently use while loops in your PowerShell scripts to achieve your automation goals.

What is a While Loop in PowerShell?

How do you use a for each loop in PowerShell?

What does $_ mean in PowerShell script?

How do I add a counter to a loop in PowerShell?

How do I skip one iteration of a loop in PowerShell?

Use the “continue” statement to skip the current iteration of a loop and move on to the next one. By placing the “continue” statement within an if condition, you can control when to skip the iteration based on certain criteria.

How do you stop an infinite loop in PowerShell?

To stop an infinite loop in PowerShell, you can use the Ctrl+C keyboard shortcut to break out of the loop. This will immediately terminate the script and return you to the PowerShell prompt.

How to Exit a While Loop Early?

Use the break keyword to terminate the loop prematurely.

What’s the Difference Between While and For Loops?

While loops continue based on a condition, but For loops iterate through a collection of items. The For loops are generally simpler for iterating through predefined data sets. While loops are useful for automating repetitive tasks where the number of iterations is not predetermined.

Can I nest while loops in PowerShell?

What happens if the condition in a while loop is always true?

If the condition in a while loop is always true, the loop will continue to execute indefinitely, resulting in an infinite loop. So, It’s important to ensure that the condition eventually becomes false to avoid infinite loops.

How can I Combine Multiple Conditions in a While Loop in PowerShell?

In a “Do While” loop, PowerShell ensures that the code within the loop runs at least once, making it ideal for scenarios where the initial execution is necessary, and subsequent checks determine additional iterations.

What is a PowerShell Do While Loop?

Syntax of PowerShell Do While Loop

Do { # Code block to be executed
} While (condition)

Read PowerShell Do-Until Loop Examples

Now, let me show you a few examples of PowerShell do while loop.

Example 1: Simple Counter

In this example, we will create a simple counter that increments a variable from 1 to 5 using the do while loop in PowerShell.

Below is the PowerShell script.

$count = 1
Do { Write-Output "Count: $count" $count++
} While ($count -le 5)
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

I executed the above script using VS code, and you can see the output in the screenshot below:

PowerShell Do While Loop

Read While Loop in PowerShell

Example 2: User Input Validation

Here is the PowerShell script.

Do { $input = Read-Host "Please enter a number between 1 and 10"
} While (-not ($input -match '^[1-9]$|10$'))
Write-Output "You entered a valid number: $input"
Please enter a number between 1 and 10: 15
Please enter a number between 1 and 10: 5
You entered a valid number: 5

Example 3: Reading File Content

In this example, we will read the content of a file line by line until we reach the end of the file.

Below is the PowerShell script that uses a do-while loop.

$filePath = "C:\MyFolder\file.txt"
$file = Get-Content $filePath -Raw
$lines = $file -split "`r`n"
$index = 0
Do { Write-Output $lines[$index] $index++
} While ($index -lt $lines.Length)

In this example, the Get-Content cmdlet reads the entire file content into a single string, and then split into an array of lines. The Do While loop iterates through the array and prints each line until the end of the array is reached.

Read How to Handle Errors with Try-Catch in PowerShell?

Do While Loop with Conditional Logic

Let us check out how to work with do while loop with conditional logic in PowerShell.

:/>  Политики аудита изменений в Active Directory

Implement Conditional Tests

Conditional tests are essential to directing the flow of a Do While loop. These tests evaluate whether the loop should continue running. Common scenarios involve checking variable values or evaluating a function’s output.

$count = 0
Do { Write-Output $count $count++
} While ($count -lt 5)

In this script, the loop runs until $count is no longer less than 5. Each iteration evaluates the condition $count -lt 5 to decide whether to proceed.

Comparison Operators

Comparison operators form the backbone of conditional logic in loops. They define the relationship between values, allowing for precise control based on these relationships.

We can also use comparison operators for the conditional logic in do while loops in PowerShell.

Here are the common operators:

  • -eq (equal)
  • -ne (not equal)
  • -gt (greater than)
  • -lt (less than)
  • -ge (greater than or equal to)
  • -le (less than or equal to).
$value = 10
Do { Write-Output "Value: $value" $value--
} While ($value -ge 0)

Here, $value -ge 0 ensures the loop runs until $value is less than zero. Each iteration checks this condition, maintaining control over the loop’s execution.

You can see the output in the screenshot below after I executed it using VS code.

do while loop in PowerShell

Read PowerShell For Loop

Handle Multiple Conditions

Now, let me show you how to handle multiple conditions in a PowerShell do while loop.

Logical operators like -and, -or, and -not combine multiple true or false values into a single condition.

Here is an example:

$x = 1
$y = 10
Do { Write-Output "x: $x, y: $y" $x++ $y--
} While ($x -le 5 -and $y -ge 5)

In the above PowerShell script, the do-while loop continues while both $x -le 5 and $y -ge 5 are true. Logical operators ensure the loop only runs when both conditions are met.

Read Create and Use Functions in PowerShell

PowerShell do while loop with break and continue

We can use the break and continue statements to control the flow. Let me show you how to use break and continue statements within a do while loop in PowerShell.

The break statement in PowerShell completely stops a loop once a certain condition is met. For example, it can exit a do-while loop when a specific value is found in an array:

Do { $number = Get-Random -Minimum 1 -Maximum 100 if ($number -eq 50) { break } Write-Output $number
} While ($true)

You can see the output in the screenshot below:

PowerShell do while loop with break and continue

The continue statement skips the remaining code in the current iteration and moves to the next iteration of the loop:

Do { $number = Get-Random -Minimum 1 -Maximum 100 if ($number -gt 90) { continue } Write-Output $number
} While ($true)

I hope that now you have an idea of using break and continue statements in a do-while loop in PowerShell.

Conclusion

Here are a few benefits of using a do while loop in PowerShell.

  • Flexibility: Allows dynamic and repeated execution of tasks.
  • User Input Handling: Can manage inputs effectively.
  • Automation Strength: Enhances automation tasks by repeating actions as long as conditions are true.

I hope you know how to use the do while loop in PowerShell with the examples above. If you still have any questions, feel free to submit a comment below.

You may also like:

while (condition) {
# Code to execute as long as the condition is true
}

Here’s how it works:

  • The code inside the
    While
    loop’s block is executed repeatedly until the specified condition evaluates to
    $false
    .
  • If the condition is
    $true
    , the code block continues to execute. When the condition becomes
    $false
    , the loop terminates, and the script proceeds to the next statement following the loop.

Using the PowerShell While Loop

Let’s explore some practical examples of using the
While
loop in PowerShell.

Example 1: Counting Down from 5

In this example, we use a
While
loop to count down from 5 to 1:

$count = 5
while ($count -ge 1) {
Write-Host "Countdown: $count"
$count--
}

When we run this script, it will display the countdown from 5 to 1.

Example 2: Polling for a File’s Existence

Another common use case for the
While
loop is polling for the existence of a file. In this example, we use a
While
loop to check if a file exists and, once it’s found, exit the loop:

$filePath = "C:\Alkane\Alkane.txt"
while (-not (Test-Path $filePath)) {
Write-Host "File not found. Retrying..."
Start-Sleep -Seconds 2
}
Write-Host "File found!"

This script continuously checks for the existence of a file at the specified path and waits for 2 seconds between each attempt. Once the file is found, the loop terminates, and it prints “File found!” to the console.

Using the PowerShell While Loop

Using the PowerShell While Loop

One of the key features of PowerShell is its ability to loop through a set of instructions multiple times, which can greatly enhance your scripting efficiency. If you’re wondering, “How do I run a loop in PowerShell?” then this article will guide you through each type of PowerShell loop and provide examples of how to use them effectively.

Types of PowerShell loops (for loop, foreach loop, while loop, do while loop, do until loop)

To understand how to loop in PowerShell, let’s start by understanding the types of loops. Each PowerShell loop variation has its own unique syntax and usage. Understanding the differences between them will let you choose the most appropriate one for your needs.

Syntax and usage of the for loop in PowerShell

loop is a classic construct in programming languages such as PowerShell that allows you to iterate over a specified range of values. It consists of three parts: the initialization, the condition, and the iteration:

  • initialization sets the initial value of a variable.
  • condition checks if the loop should continue (e.g., by checking if the variable is less than or greater than a specific number).
  • iteration updates the variable after each iteration.

In this example, the loop will execute 10 times, starting from zero and incrementing by one in each iteration.

Syntax and usage of the foreach loop in PowerShell

loop in PowerShell is used to iterate over a collection of items, such as an array or a list. It automatically assigns each item to a variable, allowing you to perform actions on each individual item.

In this example, the loop will iterate over each item in the $collection variable, and you can access each item using the $item variable within the loop.

Syntax and usage of the while loop in PowerShell

loop in PowerShell is used when you want to repeat a set of instructions as long as a certain condition is true. It checks the condition before each iteration and exits the loop when the condition becomes false.

In this example, the loop will continue executing as long as the $condition is true.

Syntax and usage of the do while loop in PowerShell

loop in PowerShell is similar to the loop, but it checks the condition after each iteration instead of before. This means that the loop will always execute at least once, even if the condition is initially false.

Syntax and usage of the do until loop in PowerShell

loop in PowerShell is the opposite of the loop. It executes a set of instructions until a certain condition becomes true. This means that the loop will always execute at least once, even if the condition is initially true.

How do I repeat a PowerShell command?

Now that you understand the basics of how to loop in PowerShell, let’s take it a step further. One of the easiest ways to repeat a PowerShell command is by simply using a loop construct and specifying the number of times you want the command to be executed.

For example, if you want to repeat a command 5 times, you can use a loop like this:

This will execute the command five times: the $i variable will be incremented by one after each iteration, and the loop will stop once the variable’s value reaches five.

Examples of PowerShell loops

Below are a few basic examples of how you can use loops in PowerShell to automate tasks and improve your scripting efficiency.

Example 1: Printing numbers from 1 to 10 using a for loop

This will print the numbers from 1 to 10 in the PowerShell console.

Example 2: Iterating over an array using a foreach loop

This will iterate over each item in the $fruits array and print it in the PowerShell console.

Other ways to automate using PowerShell

In addition to loops, PowerShell offers many other ways to automate tasks and improve your scripting efficiency. Here are a few examples:

  1. Functions: You can define reusable functions in PowerShell to encapsulate a set of instructions and use them whenever needed.
  2. Modules:
  3. Pipelines: PowerShell pipelines enable you to chain commands together, passing the output of one command as the input to another, which can greatly simplify complex tasks.
  4. Scheduled tasks: You can use PowerShell to create scheduled tasks that automate the execution of scripts at specific times or intervals.

Conclusion

Knowing how to loop in PowerShell will give you major productivity gains, enhancing your scripting efficiency. By understanding the syntax and usage of each loop type, you can choose the most appropriate one for your specific scenario. Incorporating these techniques into your PowerShell scripting workflow will save untold hours of your IT department’s time and effort.

Learning how to loop in PowerShell is just one technique for automating repetitive tasks with PowerShell. If you need more ideas for boosting productivity and efficiency, check out our guide on automating Office 365 installation with PowerShell or our list of the top 10 repetitive helpdesk tasks to automate