The if statement in PowerShell is a core control structure used to make decisions based on conditions. It evaluates a logical expression and executes specific blocks of code depending on whether the result is true or false.
In Microsoft 365 administration, if statements are commonly used to filter users, apply conditional logic, or trigger actions based on user properties—like license status, sign-in activity, or user type.
Here’s a standard if structure in PowerShell:
if () {
# code when condition is true
} elseif () {
# code for an alternative condition
} else {
# code when all conditions are false
}
PowerShell checks each condition in order. The first true condition executes its block, and the rest are skipped. This logic can be nested within loops to apply decisions to each item in a list—such as user records from Microsoft 365.
The script below demonstrates how to loop through all Microsoft 365 users and check if they are guest users using the if statement:
$users = Get-MgUser -All -Property UserType, DisplayName
foreach ($user in $users) {
if ($user.UserType -eq 'Guest') {
Write-Host "$($user.DisplayName) is a guest user"
} else {
Write-Host "$($user.DisplayName) is not a guest user"
}
}
This script showcases how if statements can add intelligence to your Microsoft 365 automation workflows—making it easy to apply logic dynamically during bulk operations.
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