Managing users in a Microsoft 365 tenant requires efficient filtering based on various attributes, including user location. Microsoft Graph PowerShell provides a seamless way to query and manage users efficiently. In this article, we will explore how to retrieve users based on their usage location using the Get-MgUser cmdlet.
# Connect to Microsoft Graph PowerShell
Connect-MgGraph -Scopes "User.Read.All"
# Prompt the admin to enter the user location
$UserLocation = Read-Host "Enter the user location (e.g., US, UK, IN)"
# Retrieve users based on the entered location
$Users = Get-MgUser -All -Filter "usageLocation eq '$UserLocation'" -Property Id, DisplayName, UsageLocation | Select-Object Id, DisplayName, UsageLocation
# Check if any users were found
if ($Users.Count -eq 0) {
Write-Host "No users found with the specified location: $UserLocation" -ForegroundColor Yellow
} else {
# Display results
$Users | Format-Table -AutoSize
}
$Locations = @("US", "UK", "CA")
$FilterQuery = ($Locations | ForEach-Object { "usageLocation eq '$_'" }) -join " or "
$Users = Get-MgUser -All -Filter $FilterQuery -Property Id, DisplayName, UsageLocation
$Users | Export-Csv -Path "UsersByLocation.csv" -NoTypeInformation
Get-MgUser -All -Search "usageLocation:US" -Property Id, DisplayName, UsageLocation
if ($Users.Count -eq 0) {
Write-Host "No users found for '$UserLocation'. Please check the location code." -ForegroundColor Red
}
$Users | ForEach-Object {
Set-MgUserLicense -UserId $_.Id -AddLicenses @{SkuId = "ENTER_SKUID"} -RemoveLicenses @{}
}
Error | Cause | Solution |
"Cannot convert the literal 'System.Collections.Hashtable' to the expected type 'Edm.Guid'" | Incorrect format for the -AddLicenses parameter. | Use the correct format: @(@{SkuId = "<SkuId>"}). |
Insufficient Permissions | The required Graph API permissions (User.ReadWrite.All, Directory.ReadWrite.All) are not granted. | Ensure the app has appropriate permissions in Azure AD and admin consent is provided. |
License Exhausted | No available licenses in the tenant. | Check license availability using Get-MgSubscribedSku and acquire additional licenses if needed. |
Efficient license management is vital for cost optimization in Microsoft 365. By automating the reassignment of freed licenses to unlicensed users, this script ensures optimal use of your organization’s resources. Implementing such tools reduces manual overhead and enables administrators to focus on strategic tasks. Try the script today and streamline your license management process!
© m365corner.com. All Rights Reserved. Design by HTML Codex