PowerShell Basics: While Loop

Exported on 11-Nov-2021 11:34:34


This is a Blueprint on Attune of how to run a While Loop in PowerShell

The While Loop is a construct for creating a loop that runs commands in a command block as long as a conditional test evaluates to true.

It is easier to construct than a For statement because its syntax is less complicated.


Name Type Script Reference Default Value Comment
Attune Node Windows Server attuneNode This is an Attune Node
Attune Node Credentials Windows OS Credential attuneNodeCredentials This is my Attune Node Credential

1 - While Loop

Below shows the basic While statement syntax:

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

The Statement List (statement list): This is where all PowerShell commands are been written for the function to execute.

The Condition Section (condition>): This evaluates the condition to either True or False; If True the loop continues, if false it breaks out of the loop.

The example in this Blueprint first checks if the condition (the value of the variable "i" is less than the total number of strings in the array [$array]) is true, if true it then runs the commands in the script block (statement list).

The loop keeps running until the condition becomes false.

The connection details have changed from the last step.

Login as user on node

  1. Connect via RDP
    mstsc /admin /v:Attune Node
  2. Login as user {Attune Node Credentials}
  3. Then open a command prompt
This is a PowerShell Script make sure you run it with powershell.exe Click start menu, enter "powershell" in the search bar, then select the powersehll program
#Region While Loop
# The variable array ($array) is declared and holds an Array of strings.
$array = @("A", "T", "T", "U", "N", "E")

# Creates a variable "i" and assigns a numeric value of 0 to it.
$i = 0

while ($i -lt $array.Count) {
    # This echos out the present value of the string in the array when the condition is satisfied.
    # `n - it creates a new line after the message.
    # This is a print to screen CMDLET [Write-Host].
    Write-Host $array[$i] `n

    # Suspends the activity in the script for 1 second
    Start-Sleep -s 1

    # Increment the present value of $i by 1 ($i++ is the same as "$i = $i + 1"}).
#EndRegion While Loop