PowerShell Do While

What is PowerShell Do While?

The Do While loop in PowerShell is a control flow structure that executes a block of code repeatedly as long as a specified condition remains true. Unlike a standard While loop, the Do While loop always executes at least once, making it ideal for situations where you want the logic to run before checking the condition.

In Microsoft 365 scripting, Do While is often used for paginated Graph API data—such as fetching users, groups, or messages—until there's no more data to retrieve.


How PowerShell Do While Operates?

The syntax for a Do While loop is:

do {
    # Code block to execute
} while ()
                                        

Here’s how it works:

  • PowerShell runs the code block once unconditionally.
  • After that, it evaluates the condition.
  • If the condition is $true, it executes the block again.
  • The loop continues until the condition evaluates to $false.

This is particularly helpful when using the Microsoft Graph PowerShell SDK, which handles paginated responses via the @odata.nextLink or NextPageLink property when querying large datasets.


Usage Example

Below is an example that uses a Do While loop to fetch all Microsoft 365 users, continuing until no more pages exist:

Connect-MgGraph -Scopes "User.Read.All"

# Get the first page of users
$response = Get-MgUser -All -Property DisplayName, UserPrincipalName
$allUsers = @()
$allUsers += $response
                                            
# Keep fetching while NextPageLink exists
do {
    $nextPage = $response.'@odata.nextLink'
    if ($nextPage) {
    $response = Invoke-MgGraphRequest -Method GET -Uri $nextPage
    $allUsers += $response.value
}
} while ($response.'@odata.nextLink')

# Output each user's Display Name and UPN
foreach ($user in $allUsers) {
    Write-Host "User: $($user.displayName) ($($user.userPrincipalName))"
}
                                        

This script will:

  • Fetch all users using Microsoft Graph pagination,
  • Store them in $allUsers,
  • Then print each user's Display Name and UPN clearly in the console.

Did You Know? Managing Microsoft 365 applications is even easier with automation. Try our Graph PowerShell scripts to automate tasks like generating reports, cleaning up inactive Teams, or assigning licenses efficiently.

Ready to get the most out of Microsoft 365 tools? Explore our free Microsoft 365 administration tools to simplify your administrative tasks and boost productivity.

© Your Site Name. All Rights Reserved. Design by HTML Codex