PowerShell variables are symbolic names used to store data values for reuse during script execution. They allow administrators to simplify complex commands, make scripts more readable, and dynamically manipulate Microsoft 365 objects using Graph PowerShell. A variable in PowerShell starts with a dollar sign ($) followed by the name (e.g., $user, $groupId).
Variables can hold any data type—strings, integers, arrays, or objects. When working with Microsoft 365, they often store user information, group IDs, license details, or filters. You assign a value using the equals sign (=), and you can reference the stored data by simply calling the variable name later in the script.
PowerShell automatically evaluates the variable and injects its value when used in expressions, cmdlets, or pipelines. This flexibility makes variables essential in automating and managing Microsoft 365 environments.
# Store user object in $user
$user = Get-MgUser -UserId "emma.james@yourdomain.com"
Write-Host "Display Name: $($user.DisplayName)"
# Get group and store its ID in $groupId
$group = Get-MgGroup -Filter "DisplayName eq 'HR Team'"
$groupId = $group.Id
Get-MgGroupMember -GroupId $groupId
# Store all users in $allUsers
$allUsers = Get-MgUser -All
Write-Host "Total Users: $($allUsers.Count)"
# Define password settings using $passwordProfile
$passwordProfile = @{
ForceChangePasswordNextSignIn = $true
Password = "Temp@12345"
}
New-MgUser -AccountEnabled $true `
-DisplayName "New User" `
-UserPrincipalName "new.user@yourdomain.com" `
-MailNickname "newuser" `
-PasswordProfile $passwordProfile
# Get and store license SKU ID in $skuId
$skuId = (Get-MgSubscribedSku | Where-Object { $_.SkuPartNumber -eq "ENTERPRISEPACK" }).SkuId
Set-MgUserLicense -UserId "emma.james@yourdomain.com" -AddLicenses @{SkuId = $skuId} -RemoveLicenses @()
# Store filtered users from 'Finance' in $financeUsers
$financeUsers = Get-MgUser -All -Filter "Department eq 'Finance'"
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