(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisbon
PowerShell
PowerShell 1 min

Microsoft 365 management with PowerShell: users, groups and licenses

João Barros 28 de February de 2025 1 min read

Managing Microsoft 365 via the portal is inefficient beyond 50 users. PowerShell with Microsoft Graph enables full automation: onboarding, licenses, groups, Teams and security auditing.

Authenticate with Microsoft Graph

Install-Module Microsoft.Graph -Scope CurrentUser

# Interactive login with the required scopes
Connect-MgGraph -Scopes "User.ReadWrite.All","Group.ReadWrite.All","Directory.ReadWrite.All"

# Service Principal for automation
Connect-MgGraph -ClientId $env:APP_ID -TenantId $env:TENANT_ID -ClientSecretCredential $cred

Bulk-create users from a CSV

$users = Import-Csv "new_users.csv" -Encoding UTF8
# CSV: DisplayName,UPN,Department,JobTitle,Manager

foreach ($u in $users) {
    $pwd = ConvertTo-SecureString (New-Guid).ToString() -AsPlainText -Force
    $params = @{
        DisplayName       = $u.DisplayName
        UserPrincipalName = $u.UPN
        PasswordProfile   = @{ Password = (New-Guid).ToString(); ForceChangePasswordNextSignIn = $true }
        AccountEnabled    = $true
        Department        = $u.Department
        JobTitle          = $u.JobTitle
    }
    New-MgUser @params
    Write-Output "Created: $($u.UPN)"
}

Assign licenses

# See available SKUs
Get-MgSubscribedSku | Select-Object SkuPartNumber, ConsumedUnits, PrepaidUnits

# Assign an M365 Business Premium license to a user
$skuId = (Get-MgSubscribedSku | Where-Object { $_.SkuPartNumber -eq "SPB" }).SkuId
Set-MgUserLicense -UserId "user@company.com" `
    -AddLicenses @(@{ SkuId = $skuId }) `
    -RemoveLicenses @()

Unused license report

# Users with a license but no sign-in in the last 90 days
$cutoff = (Get-Date).AddDays(-90)
Get-MgUser -Filter "assignedLicenses/$count ne 0" -All |
    Where-Object { $_.SignInActivity.LastSignInDateTime -lt $cutoff -or $_.SignInActivity -eq $null } |
    Select-Object DisplayName, UserPrincipalName, SignInActivity |
    Export-Csv "inactive_licenses.csv" -NoTypeInformation

Conclusion

Microsoft Graph PowerShell replaces the old MSOL and AzureAD modules, which reached end of life. For M365 management at scale — onboarding, security audits, license reports — PowerShell + MgGraph is the most efficient combination available.

Share: