PowerShell for Windows Admins

Feb 28 2018   10:58AM GMT

PowerShell while

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

PowerShell has a number of looping structures – do; while; for; foreach. This is how the PowerShell while loop works

The while statement has the form:

while (<condition>){<statement list>}

The while loop is probably the simplest of the PowerShell loops. For example:

$x = 0
while ($x -lt 5){
Write-Host “`$x is $x”
$x++
}

gives:

$x is 0
$x is 1
$x is 2
$x is 3
$x is 4

As long as the condition is true the statement list is executed

The condition is evaluated BEFORE the loop is executed meaning that it may never run

PS> $x = 10
while ($x -lt 5){
Write-Host “`$x is $x”
$x++
}

PS>

The value of $x is greater than 4 so the loop never executes.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: