For Azure AD, use Microsoft Graph PowerShell.
Step 1: Install & Connect to Azure AD
powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
Connect-MgGraph -Scopes "User.Read.All"
Step 2: Retrieve Enabled Users from Azure AD
powershellCopyEdit$AzureEnabledUsers = Get-MgUser -Filter "accountEnabled eq true" |
Select-Object DisplayName, UserPrincipalName, Mail, Id
$AzureEnabledUsers | Format-Table -AutoSize
✅ Filters only enabled accounts
✅ Displays key details (Display Name, UPN, Email, Object ID)
🔹 Step 3: Export Azure AD Enabled Users to CSV
powershellCopyEdit$AzureEnabledUsers | Export-Csv -Path "C:\Reports\AzureEnabledUsers.csv" -NoTypeInformation -Encoding UTF8
📌 Use this report for license management, compliance checks, and security audits.
🔹 Automating the Process (Scheduled Task)
To automate this script daily or weekly, set up a PowerShell scheduled task:
1️⃣ Save the script as EnabledUsersReport.ps1
2️⃣ Open Task Scheduler → Create Basic Task
3️⃣ Set Trigger (Daily, Weekly, etc.)
4️⃣ Set Action → Start a Program → powershell.exe -File C:\Scripts\EnabledUsersReport.ps1
5️⃣ Save & Run
✅ Now, you will get automated reports without manual effort! 🚀
🔹 Summary
✅ Enabled accounts must be regularly audited to maintain security & compliance.
✅ PowerShell simplifies the process of retrieving and exporting enabled accounts.
✅ On-Prem AD & Azure AD scripts ensure comprehensive user monitoring.
✅ Automating via scheduled tasks ensures continuous and hands-free monitoring.
By implementing this automation, IT administrators can proactively identify security risks, optimize licensing, and ensure compliance.
Automating the Disabling of Inactive Accounts in Active Directory & Azure AD Using PowerShell
Introduction
Inactive user accounts pose a serious security risk to any IT environment. Accounts that remain enabled but unused can be exploited by attackers, leading to potential data breaches, unauthorized access, and compliance violations.
By automating the identification and disabling of inactive accounts in Active Directory (AD) and Azure AD, organizations can enhance security and reduce attack surfaces.
This blog provides step-by-step PowerShell scripts to:
✅ Identify inactive accounts
✅ Disable inactive users automatically
✅ Export the results for auditing
✅ Schedule the task for continuous security
🔹 Why Disable Inactive Accounts?
📌 Security – Reduce the risk of unauthorized access.
📌 Compliance – Align with industry regulations (ISO 27001, NIST, GDPR, HIPAA).
📌 License Optimization – Free up unused Microsoft 365 & Azure AD licenses.
📌 Operational Efficiency – Keep Active Directory clean and organized.
Let’s automate this process using PowerShell. 🚀
🔹 Identifying & Disabling Inactive Accounts in On-Prem Active Directory
In Active Directory, a user is considered inactive if they haven’t logged in for a specific period (e.g., 90 days).
Step 1: Install & Import the Active Directory Module
Ensure the AD module is installed before running the script:
powershellCopyEditInstall-WindowsFeature -Name RSAT-AD-PowerShell
Import-Module ActiveDirectory
Step 2: Find Inactive Users (No Login for 90 Days)
powershellCopyEdit$InactiveUsers = Get-ADUser -Filter {Enabled -eq $true} -Properties LastLogonDate |
Where-Object { $_.LastLogonDate -lt (Get-Date).AddDays(-90) } |
Select-Object DisplayName, SamAccountName, LastLogonDate, Enabled
$InactiveUsers | Format-Table -AutoSize
✅ Retrieves all enabled users
✅ Filters users who haven’t logged in for 90+ days
✅ Displays Name, Username, Last Login Date
🔹 Step 3: Disable Inactive Users
powershellCopyEdit$InactiveUsers | ForEach-Object {
Disable-ADUser -Identity $_.SamAccountName -Confirm:$false
}
Write-Host "Inactive accounts disabled successfully!" -ForegroundColor Green
📌 The accounts remain in AD but are disabled 🛑
🔹 Step 4: Export Disabled Users for Auditing
powershellCopyEdit$InactiveUsers | Export-Csv -Path "C:\Reports\DisabledUsers.csv" -NoTypeInformation -Encoding UTF8
📌 Keeps a record of disabled accounts for auditing & rollback if needed
🔹 Identifying & Disabling Inactive Users in Azure AD
For Azure AD, user inactivity is determined based on the LastSignInDateTime attribute.
Step 1: Install & Connect to Azure AD
powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
Connect-MgGraph -Scopes "User.ReadWrite.All"
Step 2: Find Inactive Azure AD Users (90 Days of Inactivity)
powershellCopyEdit$AzureInactiveUsers = Get-MgUser -Filter "accountEnabled eq true" -Property DisplayName,UserPrincipalName,SignInActivity |
Where-Object { $_.SignInActivity.LastSignInDateTime -lt (Get-Date).AddDays(-90) } |
Select-Object DisplayName, UserPrincipalName, SignInActivity.LastSignInDateTime
$AzureInactiveUsers | Format-Table -AutoSize
✅ Retrieves all enabled users
✅ Filters users who haven’t signed in for 90+ days
✅ Displays Name, UPN, Last Sign-In Date
🔹 Step 3: Disable Inactive Azure AD Users
powershellCopyEdit$AzureInactiveUsers | ForEach-Object {
Update-MgUser -UserId $_.UserPrincipalName -AccountEnabled:$false
}
Write-Host "Inactive Azure AD accounts disabled successfully!" -ForegroundColor Green
📌 Azure AD users are now disabled 🛑
🔹 Step 4: Export Disabled Azure AD Users for Auditing
powershellCopyEdit$AzureInactiveUsers | Export-Csv -Path "C:\Reports\DisabledAzureUsers.csv" -NoTypeInformation -Encoding UTF8
📌 Retains a record for compliance and rollback purposes
🔹 Automating the Process (Scheduled Task)
To automate the process, create a PowerShell script and schedule it to run periodically.
1️⃣ Save the script as DisableInactiveUsers.ps1
2️⃣ Open Task Scheduler → Create Basic Task
3️⃣ Set Trigger (e.g., Weekly, Monthly)
4️⃣ Set Action → Start a Program → powershell.exe -File C:\Scripts\DisableInactiveUsers.ps1
5️⃣ Save & Run
📌 Now, the script will run automatically, disabling inactive users on schedule.
🔹 Summary
✅ Inactive accounts are a security risk—automate their disabling.
✅ PowerShell simplifies managing on-prem AD & Azure AD users.
✅ Exporting logs ensures compliance and rollback safety.
✅ Automating with Task Scheduler keeps environments secure without manual work.
By implementing this automated approach, IT teams can enhance security, ensure compliance, and reduce risk—all with PowerShell! 🚀
Re-Enabling Disabled Users in Azure AD
For Azure AD, we need to use Microsoft Graph PowerShell.
Step 1: Install & Connect to Azure AD
powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
Connect-MgGraph -Scopes "User.ReadWrite.All"
Step 2: Find Disabled Users in Azure AD
powershellCopyEdit$DisabledAzureUsers = Get-MgUser -Filter "accountEnabled eq false" -Property DisplayName, UserPrincipalName |
Select-Object DisplayName, UserPrincipalName
$DisabledAzureUsers | Format-Table -AutoSize
✅ Lists all disabled users in Azure AD
🔹 Step 3: Re-Enable Disabled Azure AD Users
powershellCopyEdit$DisabledAzureUsers | ForEach-Object {
Update-MgUser -UserId $_.UserPrincipalName -AccountEnabled:$true
}
Write-Host "All disabled Azure AD users have been re-enabled!" -ForegroundColor Green
📌 Azure AD users are now restored and can log in again 🔄
🔹 Step 4: Export Re-Enabled Azure AD Users for Auditing
powershellCopyEdit$DisabledAzureUsers | Export-Csv -Path "C:\Reports\ReEnabledAzureUsers.csv" -NoTypeInformation -Encoding UTF8
📌 Keeps an audit log of re-enabled accounts
🔹 Automating the Re-Enablement Process (Scheduled Task)
To automate the process, create a PowerShell script and schedule it to run periodically.
1️⃣ Save the script as ReEnableUsers.ps1
2️⃣ Open Task Scheduler → Create Basic Task
3️⃣ Set Trigger (e.g., Weekly, Monthly)
4️⃣ Set Action → Start a Program → powershell.exe -File C:\Scripts\ReEnableUsers.ps1
5️⃣ Save & Run
📌 Now, the script will run automatically, checking for and re-enabling disabled users.
🔹 Summary
✅ Automating re-enablement helps streamline IT operations.
✅ PowerShell makes it easy to manage AD & Azure AD accounts.
✅ Exporting logs ensures accountability for security compliance.
✅ Task Scheduler keeps everything automated.
By implementing this automated approach, IT teams can quickly restore access when needed, without manual work. 🚀
Automating User Notifications for Account Disablement & Re-Enablement Using PowerShell
🔹 Introduction
Managing user accounts effectively requires clear communication between IT and employees. When a user’s account is disabled or re-enabled, notifying them (or their manager) reduces confusion and improves security compliance.
This blog provides PowerShell scripts to:
✅ Automatically notify users when their account is disabled
✅ Send alerts when accounts are re-enabled
✅ Email managers about account status changes
✅ Export logs for auditing
🔹 Why Automate Account Status Notifications?
📌 Security Awareness – Notifies users when access is revoked or restored.
📌 Compliance – Ensures logs are maintained for security audits.
📌 Operational Efficiency – Eliminates manual notifications from IT.
📌 User Experience – Keeps employees informed about their account status.
🔹 Prerequisites
🔹 SMTP Server or Microsoft 365 Exchange Online (for sending emails)
🔹 PowerShell module installed for Active Directory and Microsoft Graph
🔹 Step 1: Configure Email Settings
Define email settings for notifications:
powershellCopyEdit$SMTPServer = "smtp.office365.com"
$SMTPPort = 587
$FromEmail = "[email protected]"
$Credential = Get-Credential # Enter email credentials for authentication
🔹 Notifying Users When Their Account is Disabled
Step 2: Identify Recently Disabled Users
powershellCopyEdit$DisabledUsers = Get-ADUser -Filter {Enabled -eq $false} -Properties DisplayName, EmailAddress, Manager |
Select-Object DisplayName, EmailAddress, Manager
✅ Finds all recently disabled users
Step 3: Send Email Notifications
powershellCopyEditforeach ($User in $DisabledUsers) {
$Subject = "Your Account Has Been Disabled"
$Body = @"
Hello $($User.DisplayName),
Your account has been disabled due to security policies or organizational requirements.
If you need further assistance, please contact IT Support.
Best regards,
IT Support Team
"@
Send-MailMessage -To $User.EmailAddress -From $FromEmail -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $Credential
}
📌 Notifies users that their access has been disabled.
Step 4: Notify Their Manager (Optional)
If users have managers assigned in Active Directory, notify them too:
powershellCopyEditforeach ($User in $DisabledUsers) {
$Manager = Get-ADUser -Identity $User.Manager -Properties EmailAddress
if ($Manager.EmailAddress) {
$ManagerSubject = "Account Disabled Notification - $($User.DisplayName)"
$ManagerBody = @"
Hello,
The account for $($User.DisplayName) has been disabled.
Please reach out to IT if further actions are required.
Best regards,
IT Support Team
"@
Send-MailMessage -To $Manager.EmailAddress -From $FromEmail -Subject $ManagerSubject -Body $ManagerBody -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $Credential
}
}
📌 Managers are informed about user account deactivation.
🔹 Notifying Users When Their Account is Re-Enabled
Step 5: Identify Recently Re-Enabled Users
powershellCopyEdit$ReEnabledUsers = Get-ADUser -Filter {Enabled -eq $true} -Properties DisplayName, EmailAddress |
Select-Object DisplayName, EmailAddress
✅ Finds all users who were just re-enabled
Step 6: Send Account Re-Enablement Notifications
powershellCopyEditforeach ($User in $ReEnabledUsers) {
$Subject = "Your Account Has Been Re-Enabled"
$Body = @"
Hello $($User.DisplayName),
Your account has been re-enabled, and you can now log in as usual.
If you experience any issues, please contact IT Support.
Best regards,
IT Support Team
"@
Send-MailMessage -To $User.EmailAddress -From $FromEmail -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $Credential
}
📌 Notifies users that their access has been restored.
🔹 Automating Notifications for Azure AD Users
If managing Azure AD, use Microsoft Graph PowerShell.
Step 7: Install & Connect to Azure AD
powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
Connect-MgGraph -Scopes "User.ReadWrite.All", "Mail.Send"
Step 8: Identify Disabled Users in Azure AD
powershellCopyEdit$DisabledAzureUsers = Get-MgUser -Filter "accountEnabled eq false" -Property DisplayName, Mail |
Select-Object DisplayName, Mail
Step 9: Send Notification to Disabled Azure AD Users
powershellCopyEditforeach ($User in $DisabledAzureUsers) {
$Subject = "Your Account Has Been Disabled"
$Body = "Hello $($User.DisplayName),`n`nYour account has been disabled. Contact IT for assistance."
Send-MgUserMail -UserId $User.Mail -Message @{
Subject = $Subject
Body = @{ Content = $Body; ContentType = "Text" }
}
}
📌 Azure AD users will receive an email alerting them about their account status.
🔹 Automating the Process with Task Scheduler
To automate the notifications:
1️⃣ Save the script as AccountNotifications.ps1
2️⃣ Open Task Scheduler → Create Basic Task
3️⃣ Set Trigger (e.g., Daily at 8 AM)
4️⃣ Set Action → Start a Program → powershell.exe -File C:\Scripts\AccountNotifications.ps1
5️⃣ Save & Run
📌 Now, account status changes will trigger email notifications automatically.
🔹 Summary
✅ Users receive notifications when their account is disabled/re-enabled.
✅ Managers get alerts about changes to their team’s access.
✅ Automation ensures no manual emails are needed.
✅ Works for both Active Directory & Azure AD.
✅ Logs can be exported for security compliance.
By implementing this automated notification system, IT teams can streamline account management, improve communication, and enhance security awareness. 🚀
Enforcing MFA Before Re-Enabling User Accounts – PowerShell Automation
🔹 Introduction
Multi-Factor Authentication (MFA) is a crucial security layer that helps prevent unauthorized access, especially after a user account is disabled and later re-enabled. Before restoring access, it’s best practice to enforce MFA enrollment to enhance security and prevent potential account compromise.
This blog provides a PowerShell script to:
✅ Automatically check MFA status before re-enabling accounts
✅ Require MFA enrollment before re-enabling
✅ Send notifications to users and IT teams
🔹 Why Enforce MFA Before Re-Enabling Accounts?
📌 Security Enhancement – Prevents unauthorized access after re-enablement.
📌 Compliance Requirements – Many security frameworks require MFA enforcement.
📌 Risk Mitigation – Reduces the risk of compromised credentials being reused.
📌 Automation Efficiency – Ensures a seamless security-first workflow.
🔹 Prerequisites
🔹 Azure AD Module installed (Install-Module AzureAD
)
🔹 PowerShell with Admin Rights
🔹 Global Administrator or Privileged Authentication Admin Role
🔹 Step 1: Connect to Microsoft Entra ID (Azure AD)
powershellCopyEditInstall-Module -Name AzureAD -Force
Import-Module AzureAD
Connect-AzureAD
📌 This will prompt for admin credentials to authenticate.
🔹 Step 2: Identify Recently Disabled Users
powershellCopyEdit$DisabledUsers = Get-AzureADUser -All $true | Where-Object { $_.AccountEnabled -eq $false } |
Select-Object DisplayName, UserPrincipalName, ObjectId
📌 Finds all disabled user accounts.
🔹 Step 3: Check MFA Enrollment Status
powershellCopyEditforeach ($User in $DisabledUsers) {
$MFAStatus = Get-MsolUser -UserPrincipalName $User.UserPrincipalName | Select-Object -ExpandProperty StrongAuthenticationMethods
if ($MFAStatus -eq $null) {
Write-Host "MFA not enabled for $($User.DisplayName). Enforcing MFA before re-enabling..." -ForegroundColor Yellow
# Proceed to enforce MFA
} else {
Write-Host "MFA already enabled for $($User.DisplayName). Ready to re-enable." -ForegroundColor Green
}
}
📌 This script checks if MFA is enabled before proceeding.
🔹 Step 4: Enforce MFA Enrollment for Users Without MFA
powershellCopyEditforeach ($User in $DisabledUsers) {
$MFAStatus = Get-MsolUser -UserPrincipalName $User.UserPrincipalName | Select-Object -ExpandProperty StrongAuthenticationMethods
if ($MFAStatus -eq $null) {
Write-Host "Forcing MFA registration for $($User.DisplayName)..."
Set-MsolUser -UserPrincipalName $User.UserPrincipalName -StrongAuthenticationRequirements @(@{State="Enabled"; })
# Send notification email to user
$Subject = "MFA Enrollment Required Before Account Re-Enablement"
$Body = "Hello $($User.DisplayName),`n`nYour account is being re-enabled, but MFA is required before accessing your account. Please complete MFA enrollment immediately."
Send-MailMessage -To $User.UserPrincipalName -From "[email protected]" -Subject $Subject -Body $Body -SmtpServer "smtp.office365.com" -Credential (Get-Credential)
Write-Host "MFA enforced and email notification sent to $($User.DisplayName)." -ForegroundColor Cyan
}
}
📌 This forces MFA enrollment and notifies the user via email.
🔹 Step 5: Re-Enable the User Account
powershellCopyEditforeach ($User in $DisabledUsers) {
$MFAStatus = Get-MsolUser -UserPrincipalName $User.UserPrincipalName | Select-Object -ExpandProperty StrongAuthenticationMethods
if ($MFAStatus -ne $null) {
Write-Host "Re-enabling account for $($User.DisplayName)..." -ForegroundColor Green
Set-AzureADUser -ObjectId $User.ObjectId -AccountEnabled $true
# Notify the user
$Subject = "Your Account Has Been Re-Enabled"
$Body = "Hello $($User.DisplayName),`n`nYour account has been successfully re-enabled. You may now log in using MFA."
Send-MailMessage -To $User.UserPrincipalName -From "[email protected]" -Subject $Subject -Body $Body -SmtpServer "smtp.office365.com" -Credential (Get-Credential)
Write-Host "Account re-enabled and email sent to $($User.DisplayName)." -ForegroundColor Cyan
}
}
📌 Only users who have completed MFA enrollment will be re-enabled.
🔹 Automating the Process
To automate MFA enforcement before re-enabling accounts:
1️⃣ Save the script as Enforce-MFA-AccountReenable.ps1
2️⃣ Open Task Scheduler → Create Basic Task
3️⃣ Set Trigger (e.g., Daily at 8 AM)
4️⃣ Set Action → Start a Program → powershell.exe -File C:\Scripts\Enforce-MFA-AccountReenable.ps1
5️⃣ Save & Run
📌 Now, all disabled accounts must complete MFA before being re-enabled!
🔹 Summary
✅ Users cannot log in until MFA is configured
✅ Automated enforcement ensures security compliance
✅ Users and IT teams are notified via email
✅ Script works for both Active Directory & Azure AD
✅ Scheduled automation eliminates manual work
With this automation, IT teams can enforce MFA before restoring user access, ensuring security-first policies and preventing unauthorized logins. 🚀