Author: jetnmariano

  • Identifying Enabled Accounts in Azure Active Directory

    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. πŸš€

  • Viewing Conditional Access Sign-Ins via Azure AD Portal

    Before automating, you can manually check sign-in logs in Azure AD:

    1. Go to Azure AD β†’ Security β†’ Conditional Access β†’ Insights & Reporting.
    2. Use filters to view blocked sign-ins, MFA-required logins, and policy failures.
    3. Analyze sign-in failures to identify patterns or misconfigurations.

    However, manual checking is inefficientβ€”let’s automate it using PowerShell & Azure Monitor!

    Automating Conditional Access Sign-In Monitoring with PowerShell

    Step 1: Install Required PowerShell Modules

    First, ensure you have the necessary modules installed.

    powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
    

    Step 2: Connect to Microsoft Graph API

    Authenticate to retrieve sign-in logs:

    powershellCopyEditConnect-MgGraph -Scopes "AuditLog.Read.All"
    

    Step 3: Retrieve Conditional Access Sign-Ins

    powershellCopyEdit$SignIns = Get-MgAuditLogSignIn | Where-Object { $_.ConditionalAccessStatus -ne "notApplied" }
    $SignIns | Select-Object UserDisplayName, UserPrincipalName, ConditionalAccessStatus, RiskLevelDuringSignIn, ClientAppUsed, IPAddress, CreatedDateTime | Format-Table -AutoSize
    

    This script retrieves all sign-ins where Conditional Access was applied and displays relevant details.

    πŸ“Œ ConditionalAccessStatus: Displays whether access was granted, blocked, or required MFA.
    πŸ“Œ RiskLevelDuringSignIn: Shows the login’s risk score (High, Medium, Low).
    πŸ“Œ IPAddress: Helps track login attempts from suspicious locations.


    πŸ”Ή Automating Monitoring with Azure Monitor & Log Analytics

    Instead of running scripts manually, we can automate monitoring using Azure Monitor and Log Analytics.

    Step 4: Configure Log Analytics to Store Sign-In Logs

    1. Go to Azure Portal β†’ Log Analytics Workspaces.
    2. Create a new workspace (or use an existing one).
    3. Navigate to Azure AD Diagnostic Settings:
      • Select AuditLogs and SignInLogs
      • Send logs to Log Analytics.
    4. Click Save.

    Now, all sign-ins will be stored for query and automation.


    πŸ”Ή Step 5: Query Conditional Access Sign-In Logs in Azure Monitor

    Once logs are stored in Log Analytics, you can query them using Kusto Query Language (KQL):

    kqlCopyEditSigninLogs
    | where ConditionalAccessStatus == "failure"
    | project UserDisplayName, UserPrincipalName, AppDisplayName, IPAddress, ConditionalAccessPolicies, TimeGenerated
    | order by TimeGenerated desc
    

    This query identifies blocked sign-ins due to Conditional Access.


    πŸ”Ή Step 6: Set Up Alerting for Suspicious Sign-Ins

    To receive email notifications for suspicious login attempts:

    1. Go to Azure Monitor β†’ Alerts β†’ New Alert Rule.
    2. Select Log Analytics as the resource.
    3. Use the KQL query above as the condition.
    4. Set Action Group β†’ Email, SMS, or Teams notification.
    5. Click Create Alert Rule.

    πŸš€ Now, you’ll be notified of any failed Conditional Access logins!


    πŸ”Ή Summary

    βœ… Conditional Access protects against unauthorized access.
    βœ… Monitoring sign-ins ensures policies are effective.
    βœ… PowerShell & KQL queries help automate log analysis.
    βœ… Azure Monitor alerts proactively notify of threats.

    By combining Conditional Access with automated monitoring, you strengthen your organization’s security posture while reducing the risk of unauthorized access.

  • Enhancing Security with Conditional Access in Azure AD

    Introduction

    In today’s cybersecurity landscape, organizations must proactively protect their environments from threats such as phishing, ransomware, and unauthorized access attempts. One of the most effective ways to enhance security is by implementing Azure AD Conditional Access policies.

    Recently, after encountering a ransomware email attack, I configured Conditional Access to block all non-USA IP addresses, ensuring that only users within the United States could access our resources. This blog will walk you through why Conditional Access is essential, how to configure it, and how to automate it using PowerShell.


    πŸ”Ή What is Conditional Access?

    Azure AD Conditional Access is a security feature that allows organizations to enforce policies that control user access based on conditions such as:
    βœ… User location (Geo-blocking)
    βœ… Device compliance (Require Intune enrollment)
    βœ… Risk detection (Block high-risk sign-ins)
    βœ… MFA enforcement (Require multi-factor authentication)
    βœ… App & session controls (Restrict access to sensitive apps)

    These policies help organizations reduce the attack surface and protect against unauthorized access.


    πŸ”Ή Scenario: Blocking All Non-USA IPs

    One of the most common Conditional Access use cases is geo-blocking, which prevents users from signing in from outside an approved country (e.g., the USA).

    Step 1: Creating the Conditional Access Policy Manually

    1. Go to Azure AD β†’ Security β†’ Conditional Access.
    2. Click New policy β†’ Name it β€œBlock Non-USA Access.”
    3. Under Assignments:
      • Users: Select All users or specific groups.
      • Conditions:
        • Locations β†’ Include Any location
        • Exclude Trusted Locations β†’ Select United States
    4. Access Control β†’ Grant Block access.
    5. Click Create and enable the policy.

    πŸ”Ή Automating Conditional Access with PowerShell

    Instead of manually configuring policies, you can use PowerShell and Microsoft Graph API to automate Conditional Access setup.

    Step 2: Install Required PowerShell Modules

    powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser
    

    Step 3: Authenticate and Connect to Microsoft Graph

    powershellCopyEditConnect-MgGraph -Scopes "Policy.ReadWrite.ConditionalAccess"
    

    Step 4: Create a Conditional Access Policy to Block Non-USA Logins

    powershellCopyEdit$policy = @{
        displayName = "Block Non-USA IPs"
        state = "enabled"
        conditions = @{
            applications = @{
                includeApplications = @("All")
            }
            locations = @{
                includeLocations = @("All")
                excludeLocations = @("US")  # Exclude USA IPs from being blocked
            }
        }
        grantControls = @{
            builtInControls = @("Block")
        }
    }
    
    New-MgConditionalAccessPolicy -BodyParameter $policy
    

    πŸ”Ή Best Practices for Conditional Access Policies

    βœ”οΈ Always test policies in report-only mode before enabling them.
    βœ”οΈ Exclude trusted accounts (e.g., Global Admins) to prevent accidental lockouts.
    βœ”οΈ Combine Conditional Access with MFA for enhanced security.
    βœ”οΈ Review Sign-in logs to monitor failed login attempts and adjust policies.


    πŸ”Ή Summary

    Implementing Conditional Access is a crucial step in securing your environment. By blocking non-USA IPs, you prevent unauthorized access and reduce the risk of cyber threats such as ransomware attacks. Automating this setup with PowerShell ensures consistent security across your organization.

    βœ… Now, your Conditional Access policy is in place, securing your environment from global threats!

  • Provisioning a User in Azure with Email, MFA, and E3 License

    Introduction

    Provisioning users in Azure AD ensures security and compliance, especially with Multi-Factor Authentication (MFA) and proper licensing. This guide walks through setting up a new user with M365 E3 licensing using PowerShell.

    Prerequisites

    βœ” PowerShell installed
    βœ” Azure AD module installed (Install-Module AzureAD)
    βœ” Global Admin or User Admin role in Azure

    PowerShell Script

    powershellCopyEdit# Connect to Azure AD
    Connect-AzureAD
    
    # Create a new user
    $PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
    $PasswordProfile.Password = "P@ssw0rd!"
    
    New-AzureADUser -UserPrincipalName "[email protected]" `
                    -DisplayName "New User" `
                    -PasswordProfile $PasswordProfile `
                    -MailNickName "newuser" `
                    -AccountEnabled $true
    
    # Assign Microsoft 365 E3 License
    $license = Get-AzureADSubscribedSku | Where-Object {$_.SkuPartNumber -eq "ENTERPRISEPACK"}
    Set-AzureADUserLicense -ObjectId "[email protected]" -AddLicenses @(@{SkuId=$license.SkuId})
    
    # Enable MFA
    $StrongAuthRequirement = New-Object -TypeName Microsoft.Open.AzureAD.Model.StrongAuthenticationRequirement
    $StrongAuthRequirement.RelyingParty = "*"
    $StrongAuthRequirement.State = "Enabled"
    Set-MsolUser -UserPrincipalName "[email protected]" -StrongAuthenticationRequirements @($StrongAuthRequirement)
    
    Write-Host "User provisioned successfully with MFA and E3 license."
    

    βœ… Done! Your new user is now provisioned with an E3 license and MFA enforced.

  • Provision Microsoft Intune

    Install-Module -Name Microsoft.Graph.Intune
    

    βœ… Intune is provisioned.

  • Tracert: What It Is & How to Use It

    tracert google.com
    

    βœ… Tracks network routes.

  • FSMO Roles & How to Identify Servers Holding the Role

    netdom query fsmo
    

    βœ… Identifies FSMO roles.

  • Restore Domain Naming Master in VMware

    Start-VM -VMName "DomainController"
    

    βœ… Restores a crashed Domain Naming Master.

  • Provisioning an Azure VM Using PowerShell

    New-AzVM -ResourceGroupName "MyRG" -Name "MyVM" -Location "EastUS"
    

    βœ… Azure VM created successfully.

  • How to Join Laptops/Desktops to Azure AD (jetmariano.us)

    Introduction

    Joining laptops and desktops to Azure AD ensures centralized management, security compliance, and easier access to cloud resources. This guide covers both manual and PowerShell methods to join a Windows device to Azure AD.

    Prerequisites

    Before proceeding, ensure the following: βœ” The device is running Windows 10 or later
    βœ” Internet connection is available
    βœ” You have Azure AD credentials with permissions
    βœ” Intune or Azure AD Join is enabled (for auto-enrollment)
    βœ” PowerShell script execution is allowed (for automation)

    1️⃣ Manual Method: Join Windows Device to Azure AD

    1️⃣ Open Settings β†’ Accounts
    2️⃣ Click Access work or school
    3️⃣ Select Connect
    4️⃣ Click Join this device to Azure Active Directory
    5️⃣ Enter your Azure AD credentials ([email protected])
    6️⃣ Click Next, verify details, and click Join
    7️⃣ Restart the computer

    βœ… Done! The device is now part of Azure AD.

    2️⃣ PowerShell Method: Automate Azure AD Join

    If you manage multiple devices, PowerShell can save a lot of time by automating the Azure AD join process.

    πŸ”Ή Step 1: Check the Current Join Status

    powershellCopyEditGet-MDMEnrollmentStatus
    

    πŸ“Œ This command checks if the device is already joined.

    πŸ”Ή Step 2: Join the Device to Azure AD

    Use the Add-Computer command to join a machine to Azure AD.

    powershellCopyEdit$AzureTenant = "jetmariano.us"
    $User = "[email protected]"
    
    dsregcmd /join /tenant $AzureTenant /UserName $User
    

    πŸ“Œ This command forces the device to join Azure AD.

    πŸ”Ή Step 3: Verify the Join Status

    powershellCopyEditdsregcmd /status
    

    πŸ“Œ The output should show AzureAdJoined : YES


    3️⃣ Auto-Enroll Devices via Microsoft Intune

    If you’re using Intune for device management, configure Auto-Enrollment:

    1️⃣ Go to Microsoft Endpoint Manager (Intune) β†’ Devices
    2️⃣ Navigate to Enroll devices
    3️⃣ Enable Automatic Enrollment for Azure AD Joined devices
    4️⃣ Assign User Groups
    5️⃣ Click Save

    βœ… Now, all new devices will be auto-enrolled into Azure AD.


    4️⃣ Troubleshooting & Best Practices

    • Ensure DNS resolution is correct for jetmariano.us
    • Check Azure AD licenses for device management
    • Use Intune for compliance policies

    Summary

    MethodWhen to UseCommand
    ManualSingle device setupSettings β†’ Accounts β†’ Work/School
    PowerShellMultiple devicesdsregcmd /join
    Intune Auto-JoinEnterprise-wide auto-enrollmentIntune Enrollment

    βœ… Your Windows devices are now joined to Azure AD!

  • How to Set up Cross-Tenant Sync in Azure Using PowerShell

    Overview

    Cross-Tenant Synchronization in Microsoft Entra ID (formerly Azure AD) allows automatic user provisioning between trusted organizations. However, synchronization may fail if incorrect identity configurations exist. In this guide, I’ll walk you through setting up Cross-Tenant Sync using PowerShell, ensuring all required configurations are properly applied.


    Prerequisites

    Before proceeding, ensure:

    1. You have Global Administrator or Identity Governance Administrator roles.
    2. Azure AD Cross-Tenant Access Settings are configured.
    3. PowerShell for Microsoft Graph (Microsoft Graph PowerShell SDK) is installed.

    Step 1: Install and Connect to Microsoft Graph PowerShell

    Ensure you have the required module installed and connect to Microsoft Graph.

    Install Microsoft Graph PowerShell Module

    powershellCopyEditInstall-Module Microsoft.Graph -Scope CurrentUser
    

    Connect to Microsoft Graph with Required Scopes

    powershellCopyEditConnect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All", "Policy.ReadWrite.CrossTenantAccess"
    

    After running this command, sign in with your Global Admin credentials.


    Step 2: Verify and Modify Cross-Tenant Access Policy

    Check your Cross-Tenant Access Policy to confirm if synchronization is enabled.

    View Current Cross-Tenant Access Settings

    powershellCopyEditGet-MgPolicyCrossTenantAccessPolicy | Format-List
    

    Enable Cross-Tenant Sync (If Disabled)

    powershellCopyEditUpdate-MgPolicyCrossTenantAccessPolicy -DefaultInboundAccessEnabled $true -DefaultOutboundAccessEnabled $true
    

    This command ensures that inbound and outbound sync is enabled.


    Step 3: Remove Conflicting Identity Types

    If a user has Phone-based authentication (federated identity), Cross-Tenant Sync will fail. You must remove phone identities.

    Check User Identities

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    Remove Phone-Based Authentication Method

    powershellCopyEditRemove-MgUserAuthenticationMethod -UserId [email protected] -AuthenticationMethodId phone
    

    Replace [email protected] with the actual User Principal Name (UPN).

    Confirm the Change

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    Ensure that “phone” is no longer listed.


    Step 4: Configure Cross-Tenant Sync Using PowerShell

    Once identities are corrected, you can enable Cross-Tenant Sync.

    Enable Cross-Tenant Sync for a Specific Tenant

    powershellCopyEditNew-MgPolicyCrossTenantAccessPolicyConfigurationPartner -TenantId "<PartnerTenantID>" -InboundTrustType "ExternalAzureAD"
    

    Replace <PartnerTenantID> with the Tenant ID of the external organization.

    Enable Automatic User Synchronization

    powershellCopyEditSet-MgPolicyCrossTenantAccessPolicyConfigurationPartner -TenantId "<PartnerTenantID>" -AutomaticUserProvisioning $true
    

    Check Sync Status

    powershellCopyEditGet-MgPolicyCrossTenantAccessPolicyConfigurationPartner -TenantId "<PartnerTenantID>"
    

    Step 5: Test and Verify Cross-Tenant Sync

    Once configured, test the sync to ensure users are provisioned correctly.

    Force Sync for Testing

    powershellCopyEditStart-ADSyncSyncCycle -PolicyType Delta
    

    This forces an immediate Azure AD Sync to reflect recent changes.

    Check Sync Logs

    If issues persist, check the Provisioning Logs in Azure AD Portal:

    1. Go to Azure Portal β†’ Entra ID β†’ Provisioning Logs
    2. Look for Cross-Tenant Sync Errors
    3. Verify user attributes and authentication methods.

    Final Thoughts

    By following these steps, you can successfully set up Cross-Tenant Sync in Azure AD using PowerShell. Removing conflicting authentication methods like Phone-based authentication is critical for a seamless synchronization process.

    If you have any questions or need further troubleshooting, drop a comment!

  • Setting Up Cross-Tenant Sync in Azure AD Using PowerShell

    Overview

    Cross-Tenant Synchronization in Microsoft Entra ID (formerly Azure AD) allows automatic user provisioning between trusted organizations. However, synchronization may fail if incorrect identity configurations exist. In this guide, I’ll walk you through setting up Cross-Tenant Sync using PowerShell, ensuring all required configurations are properly applied.


    Prerequisites

    Before proceeding, ensure:

    1. You have Global Administrator or Identity Governance Administrator roles.
    2. Azure AD Cross-Tenant Access Settings are configured.
    3. PowerShell for Microsoft Graph (Microsoft Graph PowerShell SDK) is installed.

    Step 1: Install and Connect to Microsoft Graph PowerShell

    Ensure you have the required module installed and connect to Microsoft Graph.

    Install Microsoft Graph PowerShell Module

    powershellCopyEditInstall-Module Microsoft.Graph -Scope CurrentUser
    

    Connect to Microsoft Graph with Required Scopes

    powershellCopyEditConnect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All", "Policy.ReadWrite.CrossTenantAccess"
    

    After running this command, sign in with your Global Admin credentials.


    Step 2: Verify and Modify Cross-Tenant Access Policy

    Check your Cross-Tenant Access Policy to confirm if synchronization is enabled.

    View Current Cross-Tenant Access Settings

    powershellCopyEditGet-MgPolicyCrossTenantAccessPolicy | Format-List
    

    Enable Cross-Tenant Sync (If Disabled)

    powershellCopyEditUpdate-MgPolicyCrossTenantAccessPolicy -DefaultInboundAccessEnabled $true -DefaultOutboundAccessEnabled $true
    

    This command ensures that inbound and outbound sync is enabled.


    Step 3: Remove Conflicting Identity Types

    If a user has Phone-based authentication (federated identity), Cross-Tenant Sync will fail. You must remove phone identities.

    Check User Identities

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    Remove Phone-Based Authentication Method

    powershellCopyEditRemove-MgUserAuthenticationMethod -UserId [email protected] -AuthenticationMethodId phone
    

    Replace [email protected] with the actual User Principal Name (UPN).

    Confirm the Change

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    Ensure that “phone” is no longer listed.


    Step 4: Configure Cross-Tenant Sync Using PowerShell

    Once identities are corrected, you can enable Cross-Tenant Sync.

    Enable Cross-Tenant Sync for a Specific Tenant

    powershellCopyEditNew-MgPolicyCrossTenantAccessPolicyConfigurationPartner -TenantId "<PartnerTenantID>" -InboundTrustType "ExternalAzureAD"
    

    Replace <PartnerTenantID> with the Tenant ID of the external organization.

    Enable Automatic User Synchronization

    powershellCopyEditSet-MgPolicyCrossTenantAccessPolicyConfigurationPartner -TenantId "<PartnerTenantID>" -AutomaticUserProvisioning $true
    

    Check Sync Status

    powershellCopyEditGet-MgPolicyCrossTenantAccessPolicyConfigurationPartner -TenantId "<PartnerTenantID>"
    

    Step 5: Test and Verify Cross-Tenant Sync

    Once configured, test the sync to ensure users are provisioned correctly.

    Force Sync for Testing

    powershellCopyEditStart-ADSyncSyncCycle -PolicyType Delta
    

    This forces an immediate Azure AD Sync to reflect recent changes.

    Check Sync Logs

    If issues persist, check the Provisioning Logs in Azure AD Portal:

    1. Go to Azure Portal β†’ Entra ID β†’ Provisioning Logs
    2. Look for Cross-Tenant Sync Errors
    3. Verify user attributes and authentication methods.

    Final Thoughts

    By following these steps, you can successfully set up Cross-Tenant Sync in Azure AD using PowerShell. Removing conflicting authentication methods like Phone-based authentication is critical for a seamless synchronization process.

    If you have any questions or need further troubleshooting, drop a comment!

  • Blog

    Legal Disclaimer for JetMariano.us
    Use at Your Own Risk
    • You are responsible for testing any commands or scripts in a non-production environment before using them in live or critical systems.
    • I am not liable for any data loss, security breaches, or system failures that may occur from using the information provided.
    The content and PowerShell scripts provided on JetMariano.us are based on my personal experience working with Azure, AWS, Microsoft 365, and IT automation. While I strive to ensure accuracy, all information, scripts, and tutorials are provided “as is” with no warranties or guarantees of any kind.
    Best Practice: Always review and modify scripts according to your organization’s policies and security requirements before implementation.

    Β© 2012-2025 Jet Mariano. All Rights Reserved.
    This website and its contents, including blog posts, tutorials, PowerShell scripts, and technical guides, are protected under copyright law.
    Unauthorized reproduction, redistribution, or commercial use of the content without permission is prohibited.
    If you’d like to reference or share my content, please provide proper credit and a link to JetMariano.us.
    Error: View d08e1139bf may not exist
  • “Fixing Cross-Tenant Sync Issues in Azure: Resolving Identities Conflicts”.

    Issue: Cross-Tenant Sync Not Working Due to Identity Type Conflicts

    While configuring Azure AD Cross-Tenant Synchronization, you may encounter an issue where the synchronization process fails due to incorrect identity types assigned to user accounts. In my case, the identity type was set to phone instead of the recommended authentication method, preventing successful synchronization.

    Root Cause

    After troubleshooting with Microsoft engineers, it was identified that Cross-Tenant Sync does not work when a phone-based identity is assigned to a user. The issue arises because federated identities using phone-based authentication do not support synchronization across tenants.

    As shown in the screenshots, my user identity in Azure AD > Users > Identities was set to phone under the “Sign-in type” column. This configuration blocked the user from syncing successfully between tenants.

    Solution: Change Identity to Microsoft Authenticator

    To resolve this issue, follow these steps:

    1. Remove Phone-Based Identity

    • Navigate to Microsoft Entra Admin Center (entra.microsoft.com).
    • Go to Users > Select the affected user.
    • Under Identities, locate the phone-based identity.
    • Remove the phone-based identity to clear authentication conflicts.

    2. Enforce Microsoft Authenticator as the Primary Sign-in Method

    • Go to Authentication Methods in Azure AD.
    • Ensure Microsoft Authenticator is enabled for the affected user.
    • If needed, enforce passwordless authentication via the Microsoft Authenticator app.

    3. Reattempt Cross-Tenant Sync

    • Once the phone-based identity is removed and Microsoft Authenticator is set, retry Cross-Tenant Sync.
    • The synchronization should now proceed without issues.
error: Content is protected !!