Back to script library
Entra / Microsoft 365 · Applications

New account tracking azure automation

Test script to show how to use Azure Automation with the Microsoft Graph PowerShell SDK.

Connect & set up

Run these once per session. All scopes are read-only unless the script makes changes.

Connect-MgGraph -Identity -NoWelcome

Run it

The main script. Copy it, or download the .ps1 and run it from your console.

param(
[int] $LookbackDays = 30
)
Connect-MgGraph -Identity -NoWelcome
# Get the site identifier for the target SharePoint site. Your site URI will be different!
$Uri = "https://office365itpros.sharepoint.com/sites/Office365Adoption"
$SiteId = $Uri.Split('//')[1].split("/")[0] + ":/sites/" + $Uri.Split('//')[1].split("/")[2]
$Site = Get-MgSite -SiteId $SiteId
If (!$Site) {
Write-Output ("Unable to connect to site {0} with id {1}" -f $Uri, $SiteId)
Exit
}
$List = Get-MgSiteList -SiteId $Site.Id -Filter "displayName eq 'Tenant Statistics'"
If (!$List) {
Write-Output ("Unable to find list 'Tenant Statistics' in site {0}" -f $Site.DisplayName)
Exit
}
$Date = (Get-Date).ToUniversalTime().AddDays(-$LookbackDays).ToString("yyyy-MM-ddTHH:mm:ssZ")
[array]$RecentUsers = Get-MgUser -Filter "createdDateTime ge $Date" -Property Id, displayName, UserType, CreatedDateTime |Sort-Object UserType
If ($RecentUsers) {
Write-Output "User Accounts added in the last 30 days"
Write-Output "====================================="
$RecentUsers | Format-Table DisplayName, UserType
Write-Output ""
}
[array]$UserAccounts = Get-MgUser -All -PageSize 500 -Filter "userType eq 'Member'"
[array]$M365Groups = Get-MgGroup -Filter "groupTypes/any(c:c eq 'unified')" -All -PageSize 500
$RunDate = Get-Date -format 'dd-MMM-yyyy HH:mm:ss'
# Can only store 255 characters in a list text field
$RecentUserAccounts = $RecentUsers.DisplayName -join ', '
If ($RecentUserAccounts.length -gt 255) {
$RecentUserAccounts = $RecentUserAccounts.Substring(0, 252) + "..."
}
$NewItemParameters = @{
fields = @{
Title = 'Azure Automation Check'
Rundate = $RunDate
NumberM365Groups = $M365Groups.Count
NumberUserAccounts = $UserAccounts.Count
RecentUserAccounts = $RecentUserAccounts
}
}
$NewItem = New-MgSiteListItem -SiteId $Site.Id -ListId $List.Id -BodyParameter $NewItemParameters
If ($NewItem) {
Write-Output ("Added item to list {0}" -f $List.DisplayName)
} Else {
Write-Output "Failed to add item to list"
}

Parameters

ParameterDefaultNotes
-LookbackDays30Number of days to look back when tracking newly created accounts.
Attribution