I’m trying to (as the title suggests) clean up unused service principles in Azure entra as per the compliance, azure defender and advisor recommendations.
This is a pre-cursor to me applying for ISO compliance certification for the business.
Having got some advice from Chat GPT it’s given me this broken script …
Install-Module -Name AzureAD
Connect-AzureAD
# Export users with last sign-in date
Get-AzureADUser -All $true | ForEach-Object {
$user = $_
$lastSignIn = (Get-AzureADAuditSignInLogs -Filter "userPrincipalName eq '$($user.UserPrincipalName)'" | Sort-Object createdDateTime -Descending | Select-Object -First 1).createdDateTime
[PSCustomObject]@{
UserPrincipalName = $user.UserPrincipalName
LastSignInDateTime = $lastSignIn
}
} | Export-Csv -Path "C:tempInactiveUsers.csv" -NoTypeInformation
# Import the CSV file with inactive users
$inactiveUsers = Import-Csv -Path "C:tempInactiveUsers.csv"
# Disable users
foreach ($user in $inactiveUsers) {
if ($user.LastSignInDateTime -lt (Get-Date).AddMonths(-6)) {
Set-AzureADUser -ObjectId $user.UserPrincipalName -AccountEnabled $false
}
}
… I have several issues / questions here …
- Is this a good idea?
- The script doesn’t work so I need help fixing it
- I’m surprised there’s no means to handle what it seems should be a routine task in the UI, am I missing something?
I was thinking if I skip dropping the initial set to a file I could just re-run this on an automation account as a scheduled task, is this a good or bad idea?
0