Author: jetnmariano

  • The Importance of SIEM and Best Practices in Enterprise Security

    Introduction

    In today’s cybersecurity landscape, Security Information and Event Management (SIEM) plays a crucial role in protecting organizations from threats. A robust SIEM system centralizes security monitoring, aggregates logs, detects anomalies, and helps security teams respond to incidents in real time. However, SIEM is only one piece of a comprehensive security framework. To maximize its effectiveness, it should be integrated with other advanced security solutions such as APM tools, privileged access management (CyberArk), multi-factor authentication (Duo), and endpoint detection and response (XDR).

    The Role of SIEM in Security

    A SIEM system provides the following key functions:

    • Centralized Log Management: Aggregates and normalizes logs from different sources.
    • Real-Time Threat Detection: Uses correlation rules and AI-driven analytics to detect anomalies.
    • Incident Response: Helps security teams investigate alerts and mitigate threats.
    • Compliance & Auditing: Meets regulatory requirements for PCI-DSS, HIPAA, SOX, and Hi-Trust.

    Recommended SIEM Solutions:

    1. Splunk – Market leader in log analysis and threat detection.
    2. IBM QRadar – Integrates well with enterprise IT infrastructure.
    3. Microsoft Sentinel – Cloud-based SIEM with strong integration into Microsoft’s security ecosystem.
    4. LogRhythm – Offers automation and advanced analytics.

    Integrating APM Tools for Security & Performance Monitoring

    APM (Application Performance Monitoring) tools work alongside SIEM to ensure application security and performance. APM tools help in:

    • Detecting performance bottlenecks before they become security vulnerabilities.
    • Correlating security events with application behavior.
    • Enhancing log visibility for forensic analysis.

    Recommended APM Tools:

    1. Datadog – Offers monitoring for applications, logs, and security events.
    2. Dynatrace – AI-powered analytics for anomaly detection.
    3. New Relic – Provides application telemetry and distributed tracing.
    4. AppDynamics – Deep visibility into application performance.
    5. SolarWinds – A cost-effective alternative with performance monitoring capabilities.

    The Importance of CyberArk for Privileged Access Management

    Why Privileged Access Management (PAM) Matters? Privileged accounts are the highest-value targets for cybercriminals. CyberArk provides:

    • Credential Vaulting – Securely stores and rotates privileged credentials.
    • Session Isolation – Prevents direct access to critical systems.
    • Least Privilege Enforcement – Ensures users only have access to what they need.
    • Audit Logging – Records privileged activity for compliance.

    Best Practices: Personal vs. Admin Accounts with Duo MFA

    Many enterprises make the mistake of using a single account for both personal and administrative tasks, increasing security risks. Best practices recommend:

    • Personal Account for Day-to-Day Use:
      • No elevated privileges.
      • Limited access to sensitive data.
      • MFA enforced for login.
    • Admin Account for Privileged Tasks:
      • Protected by Duo MFA with time-based authentication every 15 minutes.
      • Password resets automatically every 15 minutes (e.g., CyberArk enforcement).
      • No direct internet access (restricted browsing and email access).

    Endpoint Protection with XDR

    Endpoints are the most vulnerable attack surface. Extended Detection and Response (XDR) solutions provide:

    • Advanced Threat Detection: AI-driven monitoring for malware, ransomware, and behavioral anomalies.
    • Automated Response: Blocks and isolates compromised endpoints.
    • Integration with SIEM & SOAR: Security teams can automate investigations and threat responses.

    Recommended XDR Solutions:

    1. Microsoft Defender XDR – Natively integrates with Microsoft’s security suite.
    2. CrowdStrike Falcon XDR – Lightweight agent with cloud-native capabilities.
    3. SentinelOne – AI-driven threat hunting.
    4. Palo Alto Cortex XDR – Strong perimeter and endpoint defense.

    Perimeter Security: Cisco MX & Cisco Umbrella

    Perimeter Security & Zero Trust Architecture A properly configured perimeter ensures that malicious traffic is blocked before it reaches endpoints or internal servers.

    • Cisco Meraki MX – Next-generation firewall with content filtering, VPN, and IPS/IDS.
    • Cisco Umbrella – Cloud-delivered security that blocks malicious domains and phishing attempts at the DNS level.

    Conclusion

    An effective security framework requires a layered defense strategy that integrates SIEM, APM, PAM, MFA, XDR, and Perimeter Security.

    By implementing these solutions, organizations ensure: βœ” Proactive threat detection and response βœ” Regulatory compliance (PCI-DSS, HIPAA, SOX, Hi-Trust) βœ” Minimized attack surface βœ” Reduced impact of security breaches

    Cybersecurity is not just about having toolsβ€”it’s about implementing the right tools, enforcing best practices, and continuously monitoring for evolving threats. The Force is always within you, but having the right technology stack ensures that you are always prepared for battle.

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • PowerShell Script: Managing Shared Mailbox Access

    Overview

    This guide provides PowerShell commands to remove user access from shared mailboxes and verify access removal in Microsoft Exchange Online.

    Prerequisites

    • Administrator privileges in Exchange Online.
    • PowerShell module for Exchange Online installed.
    • Proper authentication to Exchange Online.

    Step 1: Connect to Exchange Online

    Connect-ExchangeOnline -UserPrincipalName [email protected]

    Step 2: Remove User Access from Shared Mailboxes

    $User = "[email protected]"
    $SharedMailboxes = @("[email protected]", "[email protected]")
    
    foreach ($Mailbox in $SharedMailboxes) {
        Remove-MailboxPermission -Identity $Mailbox -User $User -AccessRights FullAccess -Confirm:$false
        Remove-RecipientPermission -Identity $Mailbox -Trustee $User -AccessRights SendAs -Confirm:$false
    }

    Step 3: Verify Access Removal

    foreach ($Mailbox in $SharedMailboxes) {
        Get-MailboxPermission -Identity $Mailbox | Where-Object { $_.User -like "$User" }
        Get-RecipientPermission -Identity $Mailbox | Where-Object { $_.Trustee -like "$User" }
    }

    If no results are returned, the user no longer has access.

    Step 4: Disconnect from Exchange Online

    Disconnect-ExchangeOnline -Confirm:$false

    Notes

    Additional Considerations

    • If users report still having access, check cached credentials or ensure changes have propagated.
    • If access needs to be reinstated, use Add-MailboxPermission and Add-RecipientPermission commands.

    This script helps maintain security and manage mailbox access efficiently within Exchange Online.

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • Automating User Offboarding in Microsoft 365 using PowerShell

    When a team member leaves your organization, it’s critical to offboard them securely and efficiently. Here’s a step-by-step PowerShell-based offboarding process that covers:

    βœ… Disabling the user in Local Active Directory
    βœ… Disabling the Azure AD account
    βœ… Removing all licenses
    βœ… Disabling MFA
    βœ… Converting the mailbox to a shared mailbox
    βœ… Granting full mailbox access to the supervisor


    Step 1 – Disable the User in Local Active Directory

    powershellCopyEditDisable-ADAccount -Identity jdoe
    

    Step 2 – Disable Azure AD User Account

    powershellCopyEditConnect-AzAccount
    Set-AzureADUser -ObjectId [email protected] -AccountEnabled $false
    

    Step 3 – Remove Microsoft 365 Licenses

    powershellCopyEditConnect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All"
    $UserId = (Get-MgUser -UserId [email protected]).Id
    Set-MgUserLicense -UserId $UserId -AddLicenses @() -RemoveLicenses @("tenant:licenseGUID")
    

    πŸ“ Replace tenant:licenseGUID with the appropriate license GUID assigned to your tenant.


    Step 4 – Disable MFA

    powershellCopyEditConnect-MsolService
    Set-MsolUser -UserPrincipalName [email protected] -StrongAuthenticationRequirements @()
    

    Step 5 – Convert Mailbox to Shared

    powershellCopyEditConnect-ExchangeOnline
    Set-Mailbox -Identity [email protected] -Type Shared
    

    Step 6 – Grant Supervisor Full Access to the Shared Mailbox

    powershellCopyEditAdd-MailboxPermission -Identity [email protected] -User [email protected] -AccessRights FullAccess -InheritanceType All
    

    Summary

    Using PowerShell for offboarding saves time and ensures consistency. Always document changes and communicate them to HR or management for final closure.

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • 10 Essential PowerShell Commands for IT Administrators

    πŸ’» PowerShell is an IT Admin’s best friendβ€”whether you’re managing Active Directory, troubleshooting network issues, or automating daily tasks. These essential commands will help you work smarter, not harder.


    πŸ”Ή 1. Find All Locked-Out Users in Active Directory

    πŸ›‘ Identify locked-out accounts instantly.

    powershellCopyEditSearch-ADAccount -LockedOut | Select-Object Name, SamAccountName, LockedOut
    

    βœ… Use Case: Quickly locate and assist locked-out users.


    πŸ”Ή 2. Unlock a User’s Account in Active Directory

    πŸ”“ Unlock a user’s account without using the GUI.

    powershellCopyEditUnlock-ADAccount -Identity jdoe
    

    βœ… Use Case: Enables IT admins to resolve lockouts in seconds.


    πŸ”Ή 3. Force a Password Reset for a User

    πŸ”„ Require a user to change their password at next login.

    powershellCopyEditSet-ADUser -Identity jdoe -PasswordNeverExpires $false -ChangePasswordAtLogon $true
    

    βœ… Use Case: Ensures security compliance without manual resets.


    πŸ”Ή 4. Retrieve System Boot Time

    πŸ–₯️ Check how long a system has been running.

    powershellCopyEdit(Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime
    

    βœ… Use Case: Displays uptime in days, hours, and minutes.


    πŸ”Ή 5. List Running Services with “Stopped” Status

    πŸš€ Check which services aren’t running.

    powershellCopyEditGet-Service | Where-Object { $_.Status -eq 'Stopped' } | Select-Object Name, DisplayName
    

    βœ… Use Case: Helps identify critical services that need restarting.


    πŸ”Ή 6. Test Internet Connectivity

    🌐 Check if a machine has an active internet connection.

    powershellCopyEditTest-NetConnection -ComputerName google.com -InformationLevel Detailed
    

    βœ… Use Case: Quick and easy network diagnostics.


    πŸ”Ή 7. Find the Last 10 Failed Login Attempts

    🚫 Track failed login attempts for security auditing.

    powershellCopyEditGet-EventLog -LogName Security -InstanceId 4625 -Newest 10
    

    βœ… Use Case: Detects brute-force attacks and failed password attempts.


    πŸ”Ή 8. Get a List of Users with Expired Passwords

    πŸ”‘ Find all users with expired passwords in Active Directory.

    powershellCopyEditSearch-ADAccount -PasswordExpired | Select-Object Name, SamAccountName
    

    βœ… Use Case: Prevents user lockouts and ensures password updates.


    πŸ”Ή 9. Get Disk Space Usage on a Server

    πŸ’Ύ Check available disk space across all drives.

    powershellCopyEditGet-PSDrive | Where-Object {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"} | 
    Select-Object Name, Used, Free
    

    βœ… Use Case: Helps avoid storage-related downtime before it happens.


    πŸ”Ή 10. List & Stop Running Processes

    ⚑ View active processes and terminate any misbehaving ones.

    powershellCopyEditGet-Process | Select-Object ProcessName, Id, CPU | Format-Table -AutoSize
    Stop-Process -Name "notepad" -Force
    

    βœ… Use Case: Quickly terminate resource-hogging processes without Task Manager.


    πŸš€ Conclusion: Work Smarter, Automate More!

    πŸ’‘ PowerShell is a game-changer for IT admins, allowing faster troubleshooting, better automation, and enhanced security monitoring. Whether you’re managing user accounts, securing systems, or optimizing network performance, these commands will save time and effort.

    πŸ–₯️ Next Steps?
    πŸ“Œ Bookmark this page and check back for more advanced PowerShell scripts!
    πŸ”— Need more automation tips? Visit the PowerShell Hub for deeper insights.

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • 10 Must-Have PowerShell Scripts for IT Troubleshooting

    PowerShell is a powerful tool for IT professionals, allowing automation, troubleshooting, and system management.
    Whether you’re handling system cleanup, retrieving Wi-Fi passwords, or managing processes, these PowerShell commands can be lifesavers.
    Here are five must-know PowerShell scripts to add to your IT arsenal.


    1. Extract All Installed Applications (For Inventory & Troubleshooting)

    Need to check what software is installed on a system? This script pulls a list of all installed applications along with their version, publisher, and installation date.

    Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
    Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
    Sort-Object DisplayName |
    Format-Table -AutoSize

    πŸ”Ή Bonus: Export the list to a CSV file for documentation:

    Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
    Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
    Export-Csv -Path "C:\InstalledApps.csv" -NoTypeInformation

    2. Find and Kill Stubborn Processes

    Have an unresponsive application? Use this script to forcefully close any running process by name.

    $processName = "Teams" # Change this to the process you want to kill
    Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process -Force

    πŸ”Ή Bonus: Convert it into a user-friendly GUI:

    Add-Type -TypeDefinition @"
    using System;
    using System.Windows.Forms;
    public class KillProcess {
        public static void Main() {
            string processName = Microsoft.VisualBasic.Interaction.InputBox("Enter process name to kill:", "Kill Process", "Teams");
            if (!string.IsNullOrEmpty(processName)) {
                System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName(processName);
                foreach (var proc in procs) {
                    proc.Kill();
                }
            }
        }
    }
    "@ -Language CSharp
    
    [KillProcess]::Main()

    3. Automate System Cleanup (Cache, Temp Files, Event Logs)

    Over time, systems accumulate temporary files that can slow them down. This command clears temporary files, cache, and event logs:

    Write-Host "Clearing Temp Files, Cache, and Event Logs..." -ForegroundColor Green
    Remove-Item -Path "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "C:\Windows\Temp\*" -Recurse -Force -ErrorAction SilentlyContinue
    Clear-EventLog -LogName Application, System, Security
    Write-Host "Cleanup Completed!" -ForegroundColor Cyan

    πŸ”Ή Bonus: Automate this cleanup by scheduling it in Task Scheduler.


    4. Retrieve Wi-Fi Passwords Saved on a PC

    Need to recover a saved Wi-Fi password? This script extracts the stored credentials for all previously connected networks:

    (netsh wlan show profile) | Select-String "\:(.+)$" | ForEach-Object { 
        $network = $_.Matches.Groups[1].Value.Trim()
        $password = (netsh wlan show profile name="$network" key=clear) | Select-String "Key Content\W+\:(.+)$"
        if ($password) { 
            Write-Host "Wi-Fi: $network | Password: $($password.Matches.Groups[1].Value.Trim())" -ForegroundColor Green 
        }
    }

    πŸ”Ή Use Case: If you’re connected to a Wi-Fi network but forgot the password, this script retrieves it instantly.


    5. Scan for Suspicious File Modifications (Forensic Command)

    This script performs a recursive scan on a target machine to find recently modified files with specific extensions and flag any that contain high-risk keywords. Ideal for forensic scenarios.

    $target = "RemoteComputerName"  # Replace with computer name or IP
    $extensions = @("*.ps1", "*.sql", "*.dll", "*.cs", "*.sln", "*.vbproj")
    $keywords = 'drop', 'truncate', 'remove', 'shutdown'
    
    $session = New-PSSession -ComputerName $target -ErrorAction SilentlyContinue
    if ($session) {
        Invoke-Command -Session $session -ScriptBlock {
            param($exts, $keywords)
            Get-ChildItem -Path "C:\" -Recurse -Include $exts -ErrorAction SilentlyContinue |
            Where-Object {
                $_.LastWriteTime -gt (Get-Date).AddDays(-90) -and
                ($_ | Select-String -Pattern ($keywords -join '|') -SimpleMatch -Quiet)
            } |
            Select-Object FullName, LastWriteTime, Length
        } -ArgumentList $extensions, $keywords | Export-Csv -Path "$env:USERPROFILE\Desktop\forensic-scan.csv" -NoTypeInformation
    
        Remove-PSSession $session
    } else {
        Write-Host "Unable to connect to $target"
    }
    

    Why it matters: This script was used during a forensic investigation while I was serving on a local government IT forensic team. Its purpose was to detect whether sensitive scripts or source code had been created, modified, or concealed on a colleague’s machine. By targeting specific file types and high-risk keywords (e.g., drop, truncate, remove, shutdown), the script helps identify signs of unauthorized automation, code tampering, or mismanagement of critical systems. It supported an internal review when key files were missing and operational stability was in question.


    6. Quick System Resource Snapshot

    # Display top 10 processes by CPU usage
    Get-Process | Sort CPU -Descending | Select -First 10
    
    # Show current CPU usage
    Get-Counter '\Processor(_Total)\% Processor Time'
    
    # Show available memory
    Get-Counter '\Memory\Available MBytes'
    
    # Summarize total, free, and used memory
    Get-WmiObject -Class Win32_OperatingSystem |
    Select-Object TotalVisibleMemorySize, FreePhysicalMemory |
    ForEach-Object {
        [PSCustomObject]@{
            'TotalMemoryMB' = [math]::Round($_.TotalVisibleMemorySize / 1024, 2)
            'FreeMemoryMB'  = [math]::Round($_.FreePhysicalMemory / 1024, 2)
            'UsedMemoryMB'  = [math]::Round(($_.TotalVisibleMemorySize - $_.FreePhysicalMemory) / 1024, 2)
        }
    }
    

    Why it matters: This comprehensive snapshot is a go-to tool for on-the-fly diagnostics. Whether you’re troubleshooting performance issues, memory leaks, or high CPU usage, this command instantly reveals which processes are draining resourcesβ€”without launching Task Manager or Performance Monitor. Ideal for quick triage during server slowdowns or SQL bottlenecks.

    7. Check System Uptime

    $uptime = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
    Write-Host "System Uptime: $($uptime.Days) Days, $($uptime.Hours) Hours, $($uptime.Minutes) Minutes" -ForegroundColor Cyan
    

    Why it matters: Quickly see how long the system has been runningβ€”helpful in determining recent reboots or crashes.

    8. Check Disk Space

    Get-PSDrive -PSProvider FileSystem | Select-Object Name, Used, Free, @{Name="Free(GB)";Expression={"{0:N2}" -f ($_.Free / 1GB)}}
    

    Why it matters: Instantly assess available drive space and avoid unexpected application or SQL failures due to low disk capacity.

    9. Review Event Logs (System Errors Only)

    Get-EventLog -LogName System -EntryType Error -Newest 20 | Format-Table TimeGenerated, Source, EventID, Message -AutoSize
    

    Why it matters: Check for hardware, driver, or system errors logged in the last eventsβ€”critical when troubleshooting.

    10. Forensic Script Scan – Local Machine Analysis

    This script performs a forensic scan of the local machine, identifying recently modified files with common scripting and development extensions. It’s ideal for monitoring changes or performing audits.

    $targetPath = "C:\"
    $extensions = '*.ps1', '*.php', '*.sql', '*.bat', '*.cmd', '*.vbs', '*.js', '*.dll', '*.config', '*.json'
    $outputPath = "C:\Temp\ScriptAuditReport.csv"
    
    Get-ChildItem -Path $targetPath -Include $extensions -Recurse -ErrorAction SilentlyContinue |
    Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-90) } |
    Sort-Object LastWriteTime -Descending |
    Select-Object FullName, LastWriteTime |
    Export-Csv $outputPath -NoTypeInformation
    
    

    Why it matters: Use this script when you suspect undocumented code changes, malicious automation, or hidden activity on a machine. It pinpoints recently altered files with extensions commonly used for scripting or system manipulation. Ideal for incident response or auditing newly repurposed systems.

    Final Thoughts

    PowerShell is a must-have tool for IT professionals. These scripts help automate tasks, troubleshoot issues, and improve system efficiency. Which of these commands do you find most useful? Let me know in the comments!

    πŸš€ Stay tuned for more PowerShell tips and tricks!

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • How to Create and Manage a Shared Mailbox in Microsoft 365 Using PowerShell

    Introduction

    A shared mailbox allows multiple users to send and receive emails from a common address, making collaboration easier for teams. This guide walks you through creating a shared mailbox, assigning permissions, and verifying settings using PowerShell.

    Using PowerShell provides faster and more efficient management, especially when handling multiple mailboxes.


    πŸ”Ή Step 1: Connect to Microsoft 365 PowerShell

    Before creating the shared mailbox, connect to Exchange Online.

    Run the following command:

    powershellCopyEditConnect-ExchangeOnline -UserPrincipalName [email protected]
    

    πŸ“Œ Replace [email protected] with your admin account email.


    πŸ”Ή Step 2: Create the Shared Mailbox

    Use this PowerShell command to create a shared mailbox:

    powershellCopyEditNew-Mailbox -Shared -Name "TeamMailbox" -DisplayName "Team Shared Mailbox" -PrimarySmtpAddress "[email protected]"
    

    πŸ“Œ Replace "TeamMailbox" and "[email protected]" with your preferred mailbox name and email address.


    πŸ”Ή Step 3: Assign Permissions

    Once the mailbox is created, grant access to specific users.

    Grant Full Access (Allows users to manage the mailbox)

    powershellCopyEditAdd-MailboxPermission -Identity "[email protected]" -User "[email protected]" -AccessRights FullAccess -InheritanceType All
    

    Grant Send As Permission (Allows users to send emails from the shared mailbox)

    powershellCopyEditAdd-RecipientPermission -Identity "[email protected]" -Trustee "[email protected]" -AccessRights SendAs -Confirm:$false
    

    πŸ“Œ Replace "[email protected]" with the email of the user who needs access.


    πŸ”Ή Step 4: Verify the Shared Mailbox and Permissions

    Once configured, verify that the mailbox exists and has the correct settings.

    Check Mailbox Details

    powershellCopyEditGet-Mailbox -Identity "[email protected]" | Format-List DisplayName,PrimarySmtpAddress,RecipientTypeDetails
    

    List Users with Full Access

    powershellCopyEditGet-MailboxPermission -Identity "[email protected]" | Where-Object { $_.AccessRights -eq "FullAccess" -and $_.User -notlike "NT AUTHORITY\SELF" } | Select-Object User,AccessRights
    

    List Users with Send As Permission

    powershellCopyEditGet-RecipientPermission -Identity "[email protected]" | Where-Object { $_.AccessRights -eq "SendAs" } | Select-Object Trustee,AccessRights
    

    πŸ”Ή Step 5: Confirm the Shared Mailbox in Microsoft 365

    You can also check the mailbox in Microsoft 365 Admin Center:

    1️⃣ Sign in to Microsoft Admin Center.
    2️⃣ Go to Exchange Admin Center β†’ Recipients β†’ Shared.
    3️⃣ Locate the mailbox and confirm the settings.


    πŸš€ Conclusion

    By following these steps, you can create, manage, and verify a shared mailbox using PowerShell.

    βœ” No license required
    βœ” Centralized team email management
    βœ” Easier collaboration

    πŸ’¬ How do you manage shared mailboxes in your organization? Share your best practices in the comments below! ⬇️

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • Managing VMware with PowerCLI: Essential PowerShell Commands

    Introduction VMware PowerCLI is a powerful tool that allows administrators to manage VMware environments using PowerShell. Whether you need to create virtual machines, check resource usage, or troubleshoot storage capacity, PowerCLI provides a streamlined approach to VMware management. Below is a guide to setting up PowerCLI and using essential commands for day-to-day VMware administration.


    Step 1: Install and Import VMware PowerCLI

    Before running VMware-related PowerShell commands, ensure that VMware PowerCLI is installed on your system.

    Install-Module -Name VMware.PowerCLI -Scope CurrentUser -Force

    After installation, import the module:

    Import-Module VMware.PowerCLI

    If you encounter SSL/TLS certificate warnings while connecting, configure PowerCLI to ignore invalid certificates:

    Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false

    Step 2: Connect to vCenter Server

    To manage your VMware environment, you need to authenticate with vCenter:

    Connect-VIServer -Server <Your-VCenter-Server> -User <Your-Admin-User> -Password '<Your-Password>'

    Once connected, you can retrieve information about your virtual infrastructure.


    Step 3: List VMware Hosts

    To view all available VMware hosts:

    Get-VMHost

    This provides a list of all ESXi hosts, their connection status, and available resources.


    Step 4: Retrieve Virtual Machines

    To get a list of all VMs in the environment:

    Get-VM

    For details of a specific VM:

    Get-VM -Name <VM-Name>

    Step 5: Checking vSAN Datastore Usage

    One common challenge in VMware environments is monitoring vSAN datastore usage. To check storage space:

    Get-VsanSpaceUsage -Cluster <Your-Cluster-Name>

    To calculate the percentage of used space, run:

    $vsanUsage = Get-VsanSpaceUsage -Cluster <Your-Cluster-Name>
    $usedPercentage = 100 - (($vsanUsage.FreeSpaceGB / $vsanUsage.CapacityGB) * 100)
    "vSAN Datastore is currently {0:N2}% full" -f $usedPercentage

    Step 6: Creating a New Virtual Machine

    If you need to create a new VM:

    New-VM -Name <VM-Name> -VMHost <Host-Name> -Datastore <Datastore-Name> -DiskGB 50 -MemoryGB 4 -NumCPU 2

    This command creates a VM with 50GB disk, 4GB RAM, and 2 CPUs.


    Step 7: Cloning an Existing Virtual Machine

    To create a clone of an existing VM:

    New-VM -Name <New-VM-Name> -VM <Source-VM-Name> -Datastore <Datastore-Name> -VMHost <Target-Host>

    Step 8: Managing VM Power States

    To power on a VM:

    Start-VM -VM <VM-Name>

    To shut down a VM:

    Stop-VM -VM <VM-Name> -Confirm:$false

    To restart a VM:

    Restart-VM -VM <VM-Name> -Confirm:$false

    Step 9: Deleting a Virtual Machine

    If a VM is no longer needed, you can remove it permanently:

    Remove-VM -VM <VM-Name> -DeletePermanently -Confirm:$false

    Step 10: Checking for Leftover Files in vSAN

    Even after deleting a VM, some files may remain in the datastore. You can check for orphaned files:

    Get-Datastore -Name <Datastore-Name> | Get-ChildItem -Recurse | Where-Object { $_.Name -like "*<VM-Name>*" }

    To manually remove leftover files:

    Remove-Item -Path "vmstore:\<Datastore-Name>\FolderName\<VM-Name>.vmdk" -Confirm:$false

    Final Thoughts

    Using PowerCLI to manage VMware environments improves efficiency and automation. Whether you need to monitor vSAN usage, create new VMs, or automate backups, PowerCLI provides a flexible solution. Keep this guide handy for reference as you work with VMware environments.

    Have any useful PowerCLI commands that you frequently use? Share them in the comments below! πŸš€

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • How to Investigate and Secure a Compromised Microsoft 365 Account After a Phishing Attack

    Introduction

    Phishing attacks are one of the most common cybersecurity threats that IT administrators face. A single click on a malicious email link can lead to credential theft, data exfiltration, or malware infections.

    This guide provides a step-by-step approach to investigating and securing a potentially compromised account in Microsoft 365 using PowerShell and the Microsoft Security Portal.


    πŸ”Ή Immediate Response: Disconnect & Secure the Affected Computer

    Before investigating, act fast to prevent further damage:

    1️⃣ Shut down the compromised computer immediately.
    2️⃣ Disconnect from the network (unplug Ethernet, disable Wi-Fi).
    3️⃣ Reset the password for the affected user.
    4️⃣ Revoke all active sessions to log out any potential attacker.

    PowerShell Command to Revoke Sessions:

    powershellCopyEditRevoke-AzureADUserAllRefreshToken -ObjectId "[email protected]"
    

    Reset MFA to Prevent Unauthorized Re-Login:

    powershellCopyEditReset-MsolStrongAuthenticationMethodByUpn -UserPrincipalName "[email protected]"
    

    πŸ”Ή Step 1: Check for Unauthorized Sign-ins in Azure AD

    Use Azure AD Sign-in Logs to check for suspicious login attempts.

    PowerShell Command to Retrieve Sign-in Logs:

    powershellCopyEditConnect-AzureAD
    Get-AzureADAuditSignInLogs -Filter "status/errorCode ne '0'"
    

    βœ… Alternative:

    πŸ” Red Flags:

    🚩 Logins from unexpected locations or devices
    🚩 Multiple failed MFA attempts
    🚩 Impossible travel scenarios (e.g., two logins from different continents within minutes)


    πŸ”Ή Step 2: Investigate Phishing Emails Across the Organization

    If an attacker sent phishing emails to multiple employees, run a Compliance Search to identify all affected mailboxes.

    PowerShell Command to Search All Mailboxes for Suspicious Emails:

    powershellCopyEditNew-ComplianceSearch -Name "CompanyPhishingScan" -ExchangeLocation All -ContentMatchQuery 'has:attachment OR has:link'
    Start-ComplianceSearch -Identity "CompanyPhishingScan"
    

    Check Results:

    powershellCopyEditGet-ComplianceSearch -Name "CompanyPhishingScan" | Select Name, Status, Items
    

    If Phishing Emails Are Found, Remove Them:

    powershellCopyEditNew-ComplianceSearchAction -SearchName "CompanyPhishingScan" -Purge -PurgeType SoftDelete
    

    🚨 Use HardDelete only if emails must be permanently removed.


    πŸ”Ή Step 3: Check & Remove Hidden Forwarding Rules

    Attackers often set up automatic forwarding to steal emails.

    Check for Forwarding Rules:

    powershellCopyEditGet-Mailbox -Identity "[email protected]" | Select ForwardingAddress, ForwardingSmtpAddress
    

    Disable Auto-Forwarding if Found:

    powershellCopyEditSet-Mailbox -Identity "[email protected]" -ForwardingAddress $null -ForwardingSmtpAddress $null
    

    πŸ”Ή Step 4: Scan the Compromised Computer Before Reconnecting

    Since a phishing link was clicked, scan the system for malware before reconnecting to the network.

    Offline Windows Defender Scan:

    powershellCopyEditStart-MpScan -ScanType FullScan
    

    If Threats Are Found, Remove Them:

    powershellCopyEditRemove-MpThreat -AllThreats
    

    For a Deep Rootkit Scan, Use Windows Defender Offline:

    powershellCopyEditStart-MpWDOScan
    

    βœ… This will restart the system and scan before Windows boots.


    πŸ”Ή Step 5: Implement Long-Term Protection Measures

    βœ… Enable Safe Links & Safe Attachments in Microsoft Defender

    • Safe Links: Blocks phishing links before users click them.
    • Safe Attachments: Scans email attachments for malware before delivery.

    Enable Safe Links Policy:

    powershellCopyEditSet-SafeLinksPolicy -Identity "Default" -EnableSafeLinks $true -TrackClicks $true
    

    Enable Safe Attachments Policy:

    powershellCopyEditSet-MalwareFilterPolicy -Identity "Default" -EnableSafeAttachmentsForMail $true
    

    βœ… Educate Users on Phishing Awareness

    πŸ”Ή Enable the “Report Message” button in Outlook so employees can easily flag suspicious emails.
    πŸ”Ή Train employees to recognize phishing emails:
    βœ” Unexpected links
    βœ” Urgent language
    βœ” Sender impersonation


    πŸš€ Final Wrap-Up: Is the Account and System Secure?

    βœ” Account fully secured: No unauthorized logins, MFA reset, all active sessions revoked.
    βœ” Email threats removed: No phishing emails remain in any mailbox.
    βœ” PC scanned and clean: No malware detected before reconnecting.
    βœ” Long-term protections enabled: Safe Links, Safe Attachments, user education.

    βœ… By following these steps, IT admins can quickly contain and prevent phishing incidents in Microsoft 365! πŸš€


    πŸ’¬ What’s Next?

    How does your organization handle phishing attacks? Share your best practices in the comments below! ⬇️

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • How to Prevent Windows 10 Updates and Manage Remote Sessions Without Rebooting

    Introduction
    In many enterprise environments, automatic Windows 10 updates can disrupt critical applications. This guide provides step-by-step instructions on preventing updates, forcefully logging off users without rebooting, and managing remote machines efficiently using PowerShell, Command Prompt, and PsExec.


    Step 1: Prevent Windows 10 from Installing Updates

    Option 1: Disable Windows Update Service (Quick & Easy)

    1. Open Run (Win + R), type services.msc, and press Enter.
    2. Locate Windows Update in the list.
    3. Right-click and select Properties.
    4. Set Startup type to Disabled.
    5. Click Stop, then Apply and OK.

    πŸ’‘ This prevents Windows from automatically downloading and installing updates.

    Option 2: Use Group Policy to Block Updates

    1. Open Run (Win + R), type gpedit.msc, and press Enter.
    2. Navigate to:Computer Configuration β†’ Administrative Templates β†’ Windows Components β†’ Windows Update
    3. Double-click Configure Automatic Updates.
    4. Select Disabled, then click Apply and OK.

    Option 3: Delete Pending Updates Using PowerShell

    If Windows updates are already downloaded and pending installation:

    Stop-Service wuauserv -Force
    Stop-Service bits -Force
    Remove-Item -Path "C:\Windows\SoftwareDistribution\Download\*" -Recurse -Force
    Start-Service wuauserv
    Start-Service bits

    πŸ’‘ This clears pending updates, preventing them from being installed.


    Step 2: Completely Cancel Pending Updates and Remove Notification

    Option 1: Clear the Update Queue from Windows Update

    If stopping services alone doesn’t remove pending updates, run this in PowerShell:

    Remove-Item -Path "C:\Windows\WinSxS\pending.xml" -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "C:\Windows\SoftwareDistribution\*" -Recurse -Force

    πŸ’‘ This removes Windows’ record of pending updates.

    Option 2: Flush Update Status from Windows Registry

    If the notification persists, remove any registry traces of pending updates:

    Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" -Name "RebootRequired" -ErrorAction SilentlyContinue
    Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services\Pending" -ErrorAction SilentlyContinue

    πŸ’‘ This tells Windows that no updates are waiting for a reboot.

    Option 3: Reset Windows Update Components

    Run the following commands in CMD (Admin):

    net stop wuauserv
    net stop cryptsvc
    net stop bits
    net stop msiserver
    ren C:\Windows\SoftwareDistribution SoftwareDistribution.old
    ren C:\Windows\System32\catroot2 Catroot2.old
    net start wuauserv
    net start cryptsvc
    net start bits
    net start msiserver

    πŸ’‘ This resets Windows Update components so the system forgets pending updates.

    Force Windows to Acknowledge No Updates Are Pending

    Run:

    wuauclt.exe /resetauthorization /detectnow

    or

    gpupdate /force

    πŸ’‘ This forces Windows to recheck update policies and clear any pending update flags.

    Reboot Without Installing Updates

    To make sure Windows doesn’t install the update after a reboot, run:

    shutdown /r /t 0

    πŸ’‘ This reboots without triggering pending updates.


    Step 3: Remotely Log Off a User Without Rebooting

    Option 1: Using PowerShell (Requires Admin Privileges)

    1. Open PowerShell as Administrator.
    2. Run:query user /server:RemotePCName
    3. Identify the Session ID of the user you want to log off.
    4. Log them off with:logoff <SessionID> /server:RemotePCName

    πŸ’‘ This logs off the user without shutting down the VM.

    Option 2: Using PsExec (If PowerShell Remoting is Blocked)

    1. Download PsExec.
    2. Extract it to C:\PSEXEC.
    3. Open Command Prompt as Administrator.
    4. Navigate to the PsExec folder:cd C:\PSEXEC
    5. Check who is logged in:psexec \RemotePCName -u Administrator -p YourPassword query session
    6. Log off the user:psexec \RemotePCName -u Administrator -p YourPassword logoff <SessionID>

    πŸ’‘ This method works even if WinRM and RPC are blocked.

    Option 3: Using Command Prompt (WMI-Based Logoff)

    If PsExec fails, try using WMI:

    wmic /node:RemotePCName /user:Administrator /password:YourPassword computersystem where name="RemotePCName" call Win32Shutdown 4

    πŸ’‘ This forces all logged-in users to log off without rebooting! πŸš€


    Step 4: Ensure Remote Management Works for Future Use

    Once you regain access, run this on the remote VM to prevent future lockouts:

    Enable-PSRemoting -Force
    Set-Service -Name RemoteRegistry -StartupType Automatic
    New-NetFirewallRule -DisplayName "Allow RDP and RPC" -Direction Inbound -Protocol TCP -LocalPort 135,3389 -Action Allow

    πŸ’‘ This allows future remote PowerShell and PsExec commands to execute successfully.


    Conclusion

    By following this guide, you can prevent Windows 10 from automatically updating, remotely log off users without rebooting, and ensure seamless remote access to your systems. This is critical for IT environments where stability is a priority.

    Let me know if you need additional troubleshooting steps!

    Β© 2012–2025 Jet Mariano. All rights reserved.
    For usage terms, please see the Legal Disclaimer.

  • Why Azure Cloud Shell is Better?

    If you’re an IT professional or cloud enthusiast, you’ve likely used PowerShell to manage Azure resources. But did you know there’s a better way? Azure Cloud Shell offers a streamlined, cloud-based command-line experience that makes managing Azure easier than ever.


    πŸš€ What is Azure Cloud Shell?

    Azure Cloud Shell is a browser-based command-line tool that lets you manage Azure resources without the need to install or configure anything on your local machine. It supports both PowerShell and Bash, giving you flexibility depending on your workflow.


    πŸ”₯ Why Use Azure Cloud Shell Over Local PowerShell?

    βœ… Pre-installed Azure Modules – No need to manually install or update Az PowerShell modules. βœ… Persistent Environment – Your session and files persist across devices. βœ… Works on Any OS – Since it’s browser-based, you can use it on Windows, Mac, or Linux. βœ… Built-in Authentication – No need to repeatedly sign in to Azure. βœ… Seamless Access to Azure Resources – Direct integration with your Azure subscriptions. βœ… Supports Both Bash & PowerShell – Choose the scripting environment that works best for you.


    πŸ”Ž How to Access Azure Cloud Shell

    1. Go to the Azure Portal: Open portal.azure.com.
    2. Locate the Cloud Shell Icon: Look for the PowerShell logo (or the Bash icon) at the top-right of the screen.
    3. Click to Launch: This will open a terminal at the bottom of the Azure Portal.
    4. Sign In with Your Credentials: If prompted, sign in to Azure.
    5. Authenticate: If needed, go to Microsoft Device Login and enter the code displayed.

    πŸ”§ Basic Azure Cloud Shell Commands to Get Started

    πŸ”Ή Check Your Active Subscription

    Get-AzContext  # Displays your current subscription

    πŸ”Ή List All Azure Subscriptions

    Get-AzSubscription  # Shows all available subscriptions

    πŸ”Ή List All Resource Groups

    Get-AzResourceGroup  # Displays all resource groups in your active subscription

    πŸ”Ή List All Virtual Machines

    Get-AzVM  # Lists all VMs in your subscription

    πŸ”Ή Check Azure AD Users

    Get-AzADUser -First 10  # Retrieves the first 10 users in Azure AD

    πŸ”Ή Manage Storage Accounts

    Get-AzStorageAccount  # Lists all storage accounts in your subscription

    ⚑ Why IT Admins Love Azure Cloud Shell

    Azure Cloud Shell makes it easier to manage Azure environments without worrying about PowerShell version mismatches or module updates. It’s accessible from anywhere, even on a mobile device, making it a go-to tool for IT admins who need quick access to their cloud resources.


    πŸ’‘ Final Thoughts

    If you’re still using local PowerShell to manage Azure, it’s time to upgrade your workflow. Azure Cloud Shell offers convenience, security, and efficiencyβ€”all without the hassle of local configurations.

    Try it today and take your Azure management to the next level! πŸš€

  • Removing Pending Updates on Windows 10 and Windows 11

    Windows updates can sometimes cause issues, especially when they force restarts or interfere with applications. This guide will show you how to remove pending updates to prevent Windows from installing them. These steps apply to both Windows 10 and Windows 11.

    Step 1: Stop Windows Update Services

    Before removing pending updates, you need to stop the Windows Update service.

    Open Command Prompt (Admin) and run:

    net stop wuauserv
    net stop bits
    net stop cryptsvc

    Step 2: Delete Pending Updates

    Once the services are stopped, delete the update files stored in SoftwareDistribution and WinSxS.

    Command Prompt Method:

    del /f /s /q C:\Windows\SoftwareDistribution\DataStore\* 
    del /f /s /q C:\Windows\SoftwareDistribution\Download\* 
    del /f /s /q C:\Windows\WinSxS\pending.xml

    PowerShell Method:

    Remove-Item -Path "C:\Windows\SoftwareDistribution\DataStore\*" -Force -Recurse
    Remove-Item -Path "C:\Windows\SoftwareDistribution\Download\*" -Force -Recurse
    Remove-Item -Path "C:\Windows\WinSxS\pending.xml" -Force

    If access is denied to pending.xml, take ownership and modify permissions first:

    takeown /f C:\Windows\WinSxS\pending.xml /A
    icacls C:\Windows\WinSxS\pending.xml /grant Administrators:F

    Then, retry deleting the file.

    Step 3: Restart Windows Update Services

    Once files are deleted, restart the Windows Update services:

    net start wuauserv
    net start bits
    net start cryptsvc

    Windows 11 Extra Step

    On Windows 11, Tamper Protection in Windows Security may prevent modification of update files. If you encounter issues:

    1. Open Windows Security
    2. Navigate to Virus & Threat Protection > Manage Settings
    3. Disable Tamper Protection temporarily
    4. Follow the steps above and re-enable it after removal.

    Conclusion

    By following these steps, you can effectively remove pending Windows updates, preventing them from being installed. This is particularly useful for IT professionals managing production-critical systems.

  • How to Remove RDP Sessions Using CMD and PowerShell

    Introduction In IT administration, managing Remote Desktop Protocol (RDP) sessions is essential to maintain system security and performance. Whether you need to log off a disconnected session or forcefully remove an active session, using Command Prompt (CMD) or PowerShell can streamline the process. This guide will walk you through the methods to list, disconnect, and remove RDP sessions.


    Step 1: List Active RDP Sessions Before removing a session, you need to check which users are currently logged in. Run the following command in CMD:

    query session /server:localhost

    This will display all active and disconnected sessions along with their IDs.

    Alternatively, in PowerShell, use:

    qwinsta /server:localhost

    Both commands provide the session ID required to log off a user.


    Step 2: Log Off an RDP Session Once you have the session ID, you can log off a user session using CMD:

    logoff <SessionID> /server:localhost

    Example:

    logoff 2 /server:localhost

    This will terminate session ID 2.

    In PowerShell, use:

    rwinsta <SessionID>

    Example:

    rwinsta 2

    This will remove session ID 2 from the system.


    Step 3: Forcefully Remove a Stuck RDP Session If a session does not close properly, use this CMD command:

    taskkill /F /IM mstsc.exe

    This will forcefully terminate all remote desktop connections.

    In PowerShell, use:

    Stop-Process -Name mstsc -Force

    This achieves the same result.


    Conclusion Managing RDP sessions efficiently helps prevent resource exhaustion and unauthorized access. By using CMD or PowerShell, IT admins can quickly remove inactive or unresponsive RDP sessions, ensuring smooth operations. Bookmark these commands for future reference!

  • Mastering AZ-104: Essential Labs, PowerShell, and Tricky Concepts

    Introduction

    Passing the AZ-104: Microsoft Azure Administrator exam requires hands-on experience with Azure services. This guide provides essential labs, PowerShell/CLI commands, and explanations of tricky concepts to help you prepare efficiently.


    1️⃣ Compute (Virtual Machines & Availability)

    Lab: Deploy a VM using PowerShell

    New-AzVM -ResourceGroupName "TestRG" -Name "JetVM" -Location "EastUS" -Size "Standard_B2s" -Credential (Get-Credential)

    βœ… Key Concepts:

    • VM Backup & Disaster Recovery β†’ Use Azure Backup Vault.
    • High Availability β†’ Deploy VMs in Availability Zones.

    2️⃣ Networking (VNETs, NSGs, VPNs, Peering)

    Lab: Create a Virtual Network with Subnets and an NSG

    New-AzVirtualNetwork -ResourceGroupName "TestRG" -Name "JetVNet" -Location "EastUS" -AddressPrefix "10.1.0.0/16"

    βœ… Key Concepts:

    • VNet Peering vs VPN Gateway:
      • VNet Peering β†’ Low latency, same region.
      • VPN Gateway β†’ Cross-region, IPSec tunnels.

    3️⃣ Storage (Blob, Files, Disks, Backups)

    Lab: Create a Storage Account

    New-AzStorageAccount -ResourceGroupName "TestRG" -Name "jetstorage01" -SkuName "Standard_LRS" -Location "EastUS"

    βœ… Key Concepts:

    • Storage Tiers:
      • Hot β†’ Frequent access
      • Cool β†’ Infrequent access
      • Archive β†’ Long-term storage, lowest cost

    4️⃣ Identity & Access Management (IAM, RBAC, MFA)

    Lab: Assign RBAC Role to a User

    New-AzRoleAssignment -SignInName "<user-email>" -RoleDefinitionName "Reader" -Scope "/subscriptions/your-subscription-id"

    βœ… Key Concepts:

    • RBAC vs Conditional Access:
      • RBAC β†’ Controls Azure resources.
      • Conditional Access β†’ Controls sign-in policies (MFA, device compliance).

    5️⃣ Monitoring & Security (Azure Monitor, Defender for Cloud)

    Lab: Set Up Alerts for High CPU Usage

    New-AzMetricAlertRule -ResourceGroup "TestRG" -Name "CPUAlert" -TargetResourceId "/subscriptions/your-subscription-id/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/JetVM" -MetricName "Percentage CPU" -Threshold 80 -Operator GreaterThan -WindowSize 5m -EvaluationFrequency 1m

    βœ… Key Concepts:

    • Azure Monitor vs Log Analytics:
      • Azure Monitor β†’ Collects logs + metrics.
      • Log Analytics β†’ Queries & analyzes logs.

    πŸš€ Final Exam Prep Tips

    βœ… Hands-on practice in Azure Free Tier + Pluralsight Labs. βœ… Take full-length practice tests (MeasureUp, Tutorials Dojo). βœ… Master PowerShell/CLI for automation scenarios. βœ… Simulate exam conditions (time yourself, no distractions).


    πŸ“Œ Conclusion

    By following these structured labs and understanding key concepts, you’ll be well-prepared to ace AZ-104. Keep practicing, and best of luck on your certification journey! πŸš€

    πŸ“ Want more Azure tips? Follow my blog for more deep dives into Microsoft certifications and cloud solutions!

  • Securing Remote Work: How to Protect Your Computer When Using VPN and RDP

    With the rise of remote work and hybrid environments, many IT professionals access their work machines using VPN and RDP (Remote Desktop Protocol). While this setup provides flexibility, it also presents security risksβ€”especially when working in a cross-domain network or dealing with multiple IT teams.

    As an IT professional with experience in Citrix VDI for banking and enterprise security, I’ve implemented best practices to ensure my remote work setup is secure against unauthorized access. Here’s how you can do the same.


    πŸ” Understanding the Security Risks of VPN + RDP

    A typical work-from-home setup involves:
    βœ… Connecting to a corporate VPN (e.g., Cisco AnyConnect, Fortinet, or Palo Alto GlobalProtect)
    βœ… Using RDP (Remote Desktop Protocol) to access your work machine

    However, if not properly secured, this configuration could expose your computer to:
    ⚠ Unwanted access from other IT personnel within the VPN network
    ⚠ Brute-force RDP attacks if port 3389 is open
    ⚠ Drive redirection vulnerabilities, where attackers can view or copy your files
    ⚠ Misconfigured VPN routes, allowing unauthorized users to connect to your machine

    To prevent these risks, I follow a strict security protocol when using VPN and RDP.


    πŸ›‘οΈ Step-by-Step Guide: How to Secure Your Work Computer When Using VPN + RDP

    1️⃣ Enforce Network Level Authentication (NLA) for RDP

    Network Level Authentication (NLA) ensures that only authenticated users can initiate RDP sessions, blocking unauthorized login attempts.

    βœ… How to enable NLA:

    1. Open System Properties (sysdm.cpl)
    2. Go to the Remote tab
    3. βœ… Check “Allow connections only from computers running Remote Desktop with Network Level Authentication”
    4. Click Apply > OK

    πŸ”Ή Why it matters? Without NLA, an attacker can initiate an RDP connection and attempt brute-force attacks before authentication.


    2️⃣ Restrict RDP Access to VPN-Only IP Ranges

    By default, Windows allows RDP connections from any network. To prevent unauthorized access, restrict RDP connections only to your VPN subnet.

    βœ… How to block all external RDP access except your VPN subnet:

    1. Open Windows Defender Firewall
    2. Navigate to Advanced Settings > Inbound Rules
    3. Find Remote Desktop – User Mode (TCP-In)
    4. Right-click > Properties > Scope
    5. Under Remote IP Address, choose These IP addresses
    6. Add only your VPN subnet (e.g., 172.16.104.0/24)
    7. Click Apply > OK

    πŸ”Ή Why it matters? Even if someone inside your network tries to RDP into your machine, their connection will be blocked unless they are in the allowed VPN range.


    3️⃣ Disable Drive Redirection in RDP

    RDP allows drive redirection by default, which means that if an attacker gains access, they can browse and copy files from your local machine.

    βœ… How to disable RDP drive redirection:

    1. Open Group Policy Editor (gpedit.msc)
    2. Navigate to: pgsqlCopy codeComputer Configuration > Administrative Templates > Windows Components > Remote Desktop Services > Remote Desktop Session Host > Device and Resource Redirection
    3. Find “Do not allow drive redirection”
    4. Set it to Enabled
    5. Click Apply > OK

    πŸ”Ή Why it matters? This prevents your local drives from being exposed during RDP sessions.


    4️⃣ Monitor RDP Access Logs for Unauthorized Connections

    Since you’re the only one RDPing into your machine, it’s important to monitor login attempts to detect any suspicious activity.

    βœ… How to check RDP login logs in Event Viewer:

    1. Open Event Viewer (eventvwr.msc)
    2. Navigate to: nginxCopy codeWindows Logs > Security
    3. Look for:
      • Event ID 4624 (successful logins)
      • Event ID 4625 (failed logins)

    πŸ”Ή Why it matters? If you see failed logins from unknown IPs, someone may be trying to brute-force your RDP connection.


    5️⃣ Disable Remote Access for Unauthorized Users

    IT admins in your network may have elevated privileges, allowing them to remotely manage your system. To block unauthorized admin access, you can disable remote administration tools.

    βœ… How to remove unauthorized administrators:

    1. Open PowerShell as Administrator
    2. Run the following command to list local administrators: powershellCopy codenet localgroup Administrators
    3. If you see any unauthorized users, remove them: powershellCopy codenet localgroup Administrators "DOMAIN\Username" /delete

    πŸ”Ή Why it matters? Even with VPN access, they won’t be able to take control of your system.


    πŸ’‘ Alternative: Using Citrix VDI Instead of RDP for Secure Access

    Since I’ve worked with Citrix Virtual Desktop Infrastructure (VDI) for banks, I know that virtual desktops eliminate most RDP risks. Instead of exposing RDP ports, a Citrix setup allows users to access their workstations securely via a web portal.

    βœ… Why Citrix VDI is better than RDP over VPN:
    πŸš€ No direct RDP connection – Reduces attack surface
    πŸš€ User sessions are isolated – Prevents unauthorized access
    πŸš€ Secured with multi-factor authentication (MFA) – Extra security

    If your organization supports it, using Citrix or Windows Remote Desktop Web Access (RD Web) is a safer alternative.


    πŸ”Ž Final Thoughts

    Working remotely via VPN + RDP is convenient, but it must be properly secured to prevent unauthorized access and IT snooping. By implementing:
    βœ… Network Level Authentication (NLA)
    βœ… Restricting RDP to VPN-only IP ranges
    βœ… Disabling drive redirection
    βœ… Monitoring login logs
    βœ… Removing unauthorized admin users

    You can ensure that your remote work environment remains private and secure.

    πŸ”Ή If you’re managing an enterprise network, consider moving to Citrix VDI or Windows RD Web for an extra layer of security.

    πŸ’‘ Have questions about securing your remote access? Drop a comment below!

  • Cross-Tenant Sync and Multiple Teams Profiles: Why It Happens & How to Fix It

    In modern IT environments, Cross-Tenant Synchronization (CTS) is essential for organizations managing multiple tenants in Microsoft Entra ID. It simplifies user provisioning, automates updates, and enhances collaboration across different organizations. However, one common challenge in CTS setups is the creation of multiple Microsoft Teams profiles instead of maintaining a single unified identity.

    This issue occurs when organizations sync users between two or more tenants, but instead of retaining one Teams profile, users end up with duplicate profilesβ€”causing confusion and workflow disruptions.


    Why Do Users Get Multiple Teams Profiles?

    There are several reasons why users might experience duplicate Teams profiles in a CTS environment. Below are the most common causes and recommended solutions.


    1. B2B Collaboration vs. B2B Direct Connect

    πŸ”Ή B2B Collaboration (traditional guest access) creates separate identities in each tenant, resulting in multiple Teams profiles.

    πŸ”Ή B2B Direct Connect, on the other hand, allows seamless collaboration without generating separate guest accounts, helping to unify user identities across tenants.

    βœ… Solution: Enable B2B Direct Connect instead of B2B Collaboration to consolidate Teams profiles.

    πŸ“Œ Reference: B2B Direct Connect Overview


    2. UPN and Email Address Mismatch

    πŸ”Ή If a user’s User Principal Name (UPN) and email address don’t match across tenants, Teams may create a duplicate profile instead of linking the user’s existing profile.

    πŸ”Ή Microsoft recommends matching UPNs with the primary SMTP address to ensure identity consistency across Entra ID and Teams.

    βœ… Solution: Align UPNs and primary email addresses across all tenants to avoid duplicate profiles.

    πŸ“Œ Reference: Plan and Troubleshoot UPN Changes in Microsoft Entra ID


    3. Guest vs. Member Role in CTS

    πŸ”Ή When users are synced into another tenant, they can be assigned as either Members or Guests.

    πŸ”Ή If users are created as Guests, Teams may treat them as external users, resulting in a separate Teams profile.

    βœ… Solution: Configure Cross-Tenant Sync to assign synced users as Members instead of Guests to ensure a unified profile.

    πŸ“Œ Reference: Cross-Tenant Synchronization Overview


    4. Microsoft Teams Cache Issues

    πŸ”Ή In some cases, duplicate profiles persist due to cached credentials in Microsoft Teams.

    βœ… Solution: Clearing the Teams cache can force Teams to refresh user profiles, which may help resolve this issue.

    πŸ“Œ How to Clear Microsoft Teams Cache:

    1. Windows:
      • Close Microsoft Teams.
      • Open Run (Win + R), type %appdata%\Microsoft\Teams, and hit Enter.
      • Delete all files inside the Teams folder.
      • Restart Teams.
    2. Mac:
      • Quit Teams.
      • Open Finder > Go > Go to Folder and type ~/Library/Application Support/Microsoft/Teams.
      • Delete all contents in the Teams folder.
      • Restart Teams.
    3. Mobile (iOS/Android):
      • Go to Settings > Apps > Microsoft Teams and clear cache/storage.

    Final Thoughts

    The multiple Teams profiles issue in Cross-Tenant Synchronization setups is primarily caused by B2B configuration settings, UPN mismatches, and role assignments.

    By implementing:
    βœ… B2B Direct Connect,
    βœ… UPN and email address alignment,
    βœ… Assigning synced users as Members instead of Guests,
    βœ… Clearing Microsoft Teams cache when needed,

    Organizations can reduce duplicate profiles in Microsoft Teams and create a seamless collaboration experience across tenants.

    As Cross-Tenant Sync evolves, IT administrators should proactively monitor user identity behavior across tenants and leverage Microsoft Entra ID best practices to ensure a smooth and unified user experience.

  • Tesla & EV Blog

    Why I Love My Tesla: A Perfect Match for an IT Pro

    As an IT professional, I value efficiency, innovation, and seamless automationβ€”qualities that define both my work and my Tesla. Owning a Tesla isn’t just about having an electric vehicle; it’s about experiencing a car that evolves over time, adapts to my needs, and offers a tech-driven lifestyle that aligns perfectly with my mindset.

    Tesla’s 2025.8 Update: My Hands-On Experience & Favorite Features

    One of the things I love about owning a Tesla Model 3 is that it keeps evolvingβ€”just like an IT professional like me. Thanks to over-the-air (OTA) updates, my car doesn’t just stay relevant; it keeps getting better.

    With the March 2025 update (2025.8), I had the chance to test out some of the newest features, and let me tell youβ€”Tesla keeps pushing boundaries. Here are my personal thoughts after experiencing this update firsthand.

    🚘 Adaptive Headlights: Better Visibility at Night

    One of the first things I noticed was the new adaptive headlight system. The high beams now automatically adjust based on road conditions, improving nighttime driving. It feels smoother, smarter, and makes night driving less stressfulβ€”especially on dark Utah highways.

    🧠 Grok Smart Assistant: Tesla’s AI Just Got Smarter

    Tesla’s new AI assistant, Grok 3, is finally here. It feels more intuitive than beforeβ€”answering questions faster and handling more complex voice commands. I tested it while adjusting settings on the go, and it’s definitely a step up from previous versions. I can already see this being a game-changer as Tesla continues refining it.

    ⛷️ Cybertruck Upgrades: Better Suspension & Cold-Weather Performance

    Although I drive a Model 3, I had the chance to check out the Cybertruck’s new adjustable suspension settings at a local Tesla meetup. Owners can now fine-tune ride height for different terrains, which is great for off-roading or heavy loads. Tesla also tweaked the cold-weather performance, improving regenerative braking and battery preconditioningβ€”huge for anyone dealing with winter conditions.

    πŸ‘€ In-Cabin Radar: Smarter Passenger Detection

    Tesla has finally enabled the in-cabin radar system in older Model Y vehicles, replacing the old seat sensors. It’s more precise and reliable, detecting passengers without any lag.

    πŸ›£οΈ Navigation Just Got Smarter

    This is one of my favorite updatesβ€”Tesla added new navigation preferences! Now, I can choose from: βœ… Least Congestion (Great for avoiding traffic) βœ… Prefer Highways (For long-distance trips) βœ… Lowest Tolls (Because who likes paying extra fees?)

    I tested these settings on a drive across town, and Tesla’s routing was definitely more optimized than before. This is a must-use feature for road trips.

    πŸš› Trailer Profiles: A Smart Addition for Haulers

    Trailer Profiles were first introduced on the Cybertruck, but now they’re coming to Model S, X, and Y. I don’t tow anything with my Model 3, but I can see this being a big deal for Tesla owners who do. Being able to save trailer settings will make it easier to track mileage and get more accurate energy usage estimates.

    🎨 Custom Wraps: Personalizing the Virtual Model

    I love that Tesla added custom wrap visualizations for Model 3. Now, I can match my on-screen car to its real lookβ€”just a small touch that makes a big difference for personalization.

    FSD and Autopilot: A Glimpse into the Future
    I love both Full Self-Driving (FSD) and Autopilot. Whether I’m commuting or on long road trips, Tesla’s driver-assist technology makes driving more relaxing.

    πŸš— FSD v12 and Earlier:
    While I still keep my hands on the wheel, the car can:
    βœ… Steer, accelerate, and brake automatically
    βœ… Navigate highways with ease
    βœ… Change lanes intelligently
    βœ… Recognize traffic lights and stop signs

    πŸ”₯ FSD v13 and Beyond:
    Tesla’s latest updates are pushing the boundaries further. There’s growing excitement about FSD v13 potentially enabling more hands-free operation, bringing it closer to full autonomy. While regulatory approval and driver supervision are still required, Tesla continues to refine the tech to make it safer and more capable.


    Final Thoughts: Tesla Keeps Innovating

    After testing the March 2025 Tesla Update (2025.8), I can confidently say that Tesla isn’t slowing down. The combination of smarter AI, better lighting, enhanced navigation, and personalization features makes this a solid upgrade.

    I’m always excited for what’s next because with Tesla, my car keeps evolving just like my IT careerβ€”always adapting, always improving.

    πŸš€ What’s your favorite feature from this update? Drop a comment below!

    No More Gas and Maintenance Hassles

    One of the biggest advantages of driving a Tesla is never having to stop at a gas station. With home charging, my car is always ready to go when I wake up. Plus, long road trips are effortless with Tesla’s Supercharger network, which continues to expand.

    Beyond gas savings, Tesla eliminates the hassle of oil changes, transmission failures, and countless other maintenance headaches that come with traditional cars. The simplicity of an electric motor means fewer moving parts, fewer breakdowns, and more time spent enjoying the drive rather than worrying about repairs.

    A Car That Evolves: The Power of Over-the-Air Updates

    My Tesla isn’t just a carβ€”it’s a software-driven machine. Unlike traditional vehicles that become outdated over time, my Tesla gets better with every update.

    Right now, I’m running Tesla’s 2025.2.8 software update, which I received over-the-air without ever visiting a service center. These updates continuously improve the car’s performance, battery efficiency, entertainment features, and driver-assist technology. It feels like waking up to a brand-new car every few months.

    FSD and Autopilot: A Glimpse into the Future

    I love both Full Self-Driving (FSD) and Autopilot. Whether I’m commuting or on long road trips, Tesla’s driver-assist technology makes the experience more relaxing. While I still keep my hands on the wheel, the car can:
    βœ… Steer, accelerate, and brake automatically
    βœ… Navigate highways with ease
    βœ… Change lanes intelligently
    βœ… Recognize traffic lights and stop signs

    With every update, Tesla pushes the boundaries of what’s possible, making FSD smarter and safer.

    Minimalist Design: Simplicity Meets Functionality

    Inside my Tesla, I enjoy a clean, distraction-free cabin. There are no unnecessary buttonsβ€”just a sleek 15-inch touchscreen that controls everything seamlessly. The interface is intuitive, responsive, and regularly updated for a smoother experience.

    Plus, with wireless phone charging, premium sound, and an expansive glass roof, Tesla blends technology with comfort in a way that makes driving enjoyable every day.

    Convenience at Its Best: Keyless Entry and Smart Features

    One of my favorite features is the hands-free trunk opening. When I’m carrying groceries in both hands, I don’t need to fumble for keysβ€”the trunk automatically opens as long as I have my Apple Watch with me.

    Tesla’s keyless entry means I never have to take out a key fobβ€”my phone or watch acts as the key, unlocking the car the moment I approach. It’s small details like this that make Tesla stand out.

    Fast, Smooth, and Silent

    Tesla’s acceleration is nothing short of thrilling. With instant torque, there’s no lagβ€”just pure, smooth power. Whether I need to merge onto the freeway or pass a slow-moving vehicle, my Tesla responds immediately.

    And let’s not forget the quiet ride. With no engine noise, every drive is peaceful, making road trips feel effortless.

    Conclusion: A Perfect Match for an IT Pro

    My Tesla isn’t just a carβ€”it’s a technology powerhouse that perfectly complements my profession as an IT expert. From over-the-air updates to intelligent automation, Tesla embodies everything I love about cutting-edge innovation.

    It’s efficient, fast, futuristic, andβ€”most importantlyβ€”it makes every drive something to look forward to.

    πŸš—βš‘ Once you drive a Tesla, there’s no going back.

  • Azure Application Proxy: A Secure Remote Access Solution

    Introduction

    With the rise of remote work and cloud-based applications, organizations need secure and efficient ways to provide access to internal applications. Azure Application Proxy is a lightweight, cloud-based solution that allows users to access on-premises applications securely from anywhere without a VPN.

    This blog will cover:
    βœ… What is Azure App Proxy?
    βœ… How it works
    βœ… Prerequisites for deployment
    βœ… Step-by-step setup using Azure Portal & PowerShell
    βœ… Best practices for security & performance


    πŸ”Ή What is Azure Application Proxy?

    Azure Application Proxy is a cloud-based service in Microsoft Entra ID (formerly Azure AD) that provides secure remote access to on-premises web applications.
    βœ” No VPN required – Reduces complexity & costs
    βœ” Single Sign-On (SSO) – Seamless authentication via Entra ID
    βœ” Secure & Scalable – Uses reverse proxy architecture
    βœ” Conditional Access Support – Controls access based on risk level

    πŸ’‘ Common Use Cases

    πŸ”Ή Access legacy web apps from any device
    πŸ”Ή Provide secure extranet access for partners
    πŸ”Ή Replace traditional VPNs for application access
    πŸ”Ή Enable remote access to intranet apps


    πŸ”Ή How Does Azure App Proxy Work?

    Azure App Proxy consists of two main components:

    1. Application Proxy Service (Cloud-based)
      • Runs in Azure
      • Authenticates users via Entra ID
      • Sends requests to the on-premises connector
    2. Application Proxy Connector (On-Premises Agent)
      • Installed inside the corporate network
      • Forwards authenticated requests to internal applications
      • Uses outbound traffic only (no firewall holes needed)

    πŸ“Œ Architecture Flow

    1️⃣ User accesses app-protected URL
    2️⃣ Azure App Proxy authenticates the user via Entra ID
    3️⃣ Request is forwarded to the on-premises App Proxy Connector
    4️⃣ Connector retrieves the response & sends it back via Azure Proxy


    πŸ”Ή Prerequisites

    Before deploying Azure App Proxy, ensure:
    βœ… Microsoft Entra ID (Azure AD) P1 or P2 license
    βœ… An on-premises Windows Server (2016+) to install the connector
    βœ… Outbound internet access on the connector server
    βœ… Domain-joined or cloud-hybrid environment (if using SSO)
    βœ… App must use HTTP/HTTPS (No TCP/UDP apps)


    πŸ› οΈ Deploying Azure App Proxy

    πŸ”Ή Step 1: Install Application Proxy Connector

    πŸ“Œ Run the following PowerShell command on your Windows Server:

    powershellCopyEditInvoke-WebRequest -Uri https://aka.ms/aadappproxy -OutFile "AADAppProxyInstaller.exe"
    Start-Process "AADAppProxyInstaller.exe" -ArgumentList "/quiet" -Wait
    

    πŸ‘‰ Sign in with Global Admin credentials to register the connector.

    Verify that the connector is running:

    powershellCopyEditGet-Service | Where-Object { $_.DisplayName -match "Application Proxy Connector" }
    

    πŸ”Ή Step 2: Register the Application in Azure

    1️⃣ Sign into the Azure Portal
    2️⃣ Go to Microsoft Entra ID β†’ Enterprise Applications
    3️⃣ Click New Application β†’ On-premises Application
    4️⃣ Set External URL (e.g., https://app.jetmariano.us)
    5️⃣ Set Internal URL (e.g., http://internal-app-server.local)
    6️⃣ Choose Pre-authentication method:
    βœ” Azure AD (Recommended) – Uses SSO & Conditional Access
    βœ” Passthrough – No authentication (use only if required)


    πŸ”Ή Step 3: Configure Single Sign-On (SSO) (Optional)

    If using SSO with Kerberos, configure:

    powershellCopyEditSet-WebApplicationProxyApplication -Name "InternalApp" -BackendApplicationUrl "http://internal-app.local" -ExternalApplicationUrl "https://app.jetmariano.us" -ConnectorGroupID "ConnectorGroup1" -SSOType "KerberosConstrainedDelegation"
    

    βœ… This allows seamless authentication without repeated login prompts.


    πŸ”Ή Step 4: Test & Secure the Application

    πŸ”Ή Access your external URL and verify that it works.
    πŸ”Ή Enable Conditional Access for added security.
    πŸ”Ή Restrict access based on device compliance, location, MFA, etc.


    πŸ”’ Best Practices for Azure App Proxy

    βœ” Use Azure AD Pre-authentication – Avoid exposing internal apps
    βœ” Enable Conditional Access – Enforce MFA & compliance policies
    βœ” Monitor access logs – Track login attempts & potential threats
    βœ” Use HTTPS for internal apps – Encrypt traffic end-to-end
    βœ” Scale with multiple connectors – Ensure redundancy & load balancing


    βœ… Conclusion

    Azure Application Proxy modernizes remote access by eliminating VPN dependencies and enhancing security with Azure AD SSO & Conditional Access.

    πŸš€ Next Steps:
    πŸ”Ή Explore Hybrid Azure AD Join for better identity management
    πŸ”Ή Implement Privileged Access Management (PAM) for sensitive apps
    πŸ”Ή Set up Azure AD Identity Protection to detect risk-based sign-ins

    πŸ”Ή Have you implemented Azure App Proxy? Share your experience below! πŸ’¬

  • Fixing MFA Lockout Issues & Bypass Methods in Azure AD

    Introduction

    Multi-Factor Authentication (MFA) is a crucial security measure in Microsoft Entra ID (formerly Azure AD) to protect against unauthorized access. However, users and administrators often encounter MFA lockout issues, preventing legitimate users from accessing their accounts. This can be due to device loss, incorrect configurations, or a lack of backup authentication methods.

    In this blog, we will cover: βœ… Why MFA lockout happens
    βœ… How to reset MFA for users
    βœ… Bypass methods for emergency access
    βœ… Best practices to prevent future issues


    πŸ” Why Does MFA Lockout Happen?

    MFA lockouts typically occur due to:

    • Device Change – User loses access to their phone or resets their device
    • Authenticator App Issues – User gets a new phone and doesn’t migrate the Authenticator app
    • Phone Number Change – SMS authentication fails due to a new phone number
    • Policy Restrictions – Conditional Access or legacy MFA settings prevent login
    • MFA Throttling – Too many failed attempts lock out the user

    πŸ› οΈ How to Reset MFA for a User

    If a user is locked out, an Azure AD admin can reset their MFA settings. Here’s how:

    πŸ”Ή Reset MFA via Microsoft Entra Admin Center

    1. Sign in to Microsoft Entra Admin Center as an administrator.
    2. Navigate to Users > All users
    3. Search for the affected user and select them
    4. Click Authentication methods > Require Re-register MFA
    5. Have the user sign in again and set up MFA from scratch

    πŸ”Ή Reset MFA Using PowerShell

    Admins can reset MFA via PowerShell with Microsoft Graph PowerShell.

    1️⃣ Connect to Microsoft Graph

    powershellCopyEditConnect-MgGraph -Scopes "User.ReadWrite.All"
    

    2️⃣ Find the user needing an MFA reset

    powershellCopyEditGet-MgUser -UserId [email protected] | Select-Object DisplayName,UserPrincipalName,Id
    

    3️⃣ Reset MFA settings for the user

    powershellCopyEditRevoke-MgUserAuthenticationMethod -UserId [email protected]
    

    4️⃣ Confirm the user is cleared of previous MFA methods

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    The user will now be prompted to re-enroll in MFA at their next login.


    🚨 Emergency MFA Bypass Methods

    In cases where users are locked out and immediate access is required, temporary workarounds can help.

    1️⃣ Use a Temporary Access Pass (TAP)

    A Temporary Access Pass (TAP) allows a user to log in without MFA for a limited time.

    Enable TAP:

    1. Go to Microsoft Entra Admin Center
    2. Navigate to Users > Authentication Methods
    3. Enable Temporary Access Pass policy

    Issue a TAP for the user:

    powershellCopyEditNew-MgUserAuthenticationTemporaryAccessPassMethod -UserId [email protected] -LifetimeInMinutes 30 -IsUsableOnce $true
    

    The user can now sign in using the TAP and reset their MFA.


    2️⃣ Add a Backup Authentication Method

    If a user still has access to another sign-in method, add an additional MFA option.

    Via Admin Portal:

    1. Go to Users in Entra Admin Center
    2. Select the user > Authentication methods
    3. Click Add method and enter an alternate phone number or security key

    Via PowerShell:

    powershellCopyEditNew-MgUserAuthenticationPhoneMethod -UserId [email protected] -PhoneNumber "+1234567890" -PhoneType Mobile -SmsSignInState Enabled
    

    Now, the user can verify via SMS instead.


    3️⃣ Disable MFA Temporarily

    ⚠ Warning: This is a security risk and should only be used as a last resort.

    Disable MFA for a user via PowerShell

    powershellCopyEditSet-MsolUser -UserPrincipalName [email protected] -StrongAuthenticationRequirements @()
    

    OR disable MFA for an entire tenant (not recommended):

    powershellCopyEditSet-MsolCompanySettings -PreventPerUserMFA $true
    

    Re-enable MFA as soon as possible.


    βœ… Best Practices to Prevent MFA Lockouts

    πŸ”Ή Enable Multiple Authentication Methods – Users should register both phone and Authenticator app.
    πŸ”Ή Use Temporary Access Passes (TAP) – Helps in cases of device loss.
    πŸ”Ή Educate Users on MFA Backup Codes – Encourage users to save backup codes.
    πŸ”Ή Enable Admin Recovery Options – Allow trusted admins to reset MFA.
    πŸ”Ή Monitor MFA Logs – Use Azure Sign-In Logs to track MFA failures:

    powershellCopyEditGet-MgAuditLogSignIn -Filter "status/errorCode eq 500121"
    

    πŸ“Œ Conclusion

    MFA is essential for securing accounts, but lockouts can frustrate users and disrupt productivity. By using TAP, PowerShell resets, and backup methods, admins can quickly restore access while keeping security intact.

    πŸš€ What’s next? Consider automating MFA resets with Microsoft Graph API or setting up self-service MFA reset policies for users.

    πŸ”Ή Have you experienced MFA lockout issues? What solutions worked best for you? Let’s discuss in the comments! πŸ’¬

  • Azure Single Sign-On (SSO): What It Is and How to Implement It

    Introduction to Azure SSO

    Azure Single Sign-On (SSO) is an identity authentication mechanism that allows users to log in once and gain access to multiple applications without needing to re-enter credentials. It integrates with Azure Active Directory (Azure AD) and supports modern authentication protocols like SAML, OpenID Connect (OIDC), and OAuth 2.0.

    Organizations use Azure SSO to improve security, user experience, and IT efficiency while reducing password fatigue and helpdesk requests for password resets.


    πŸ”Ή Why Use Azure SSO?

    βœ… Improves Security – Reduces password-based attacks by enforcing authentication policies.
    βœ… Enhances User Experience – Eliminates the need for multiple logins across cloud apps.
    βœ… Reduces IT Workload – Minimizes helpdesk tickets for password resets.
    βœ… Centralized Access Control – Manages authentication and access policies in one place.
    βœ… Supports Hybrid Environments – Works with cloud and on-premises apps.


    πŸ”Ή How Azure SSO Works

    Azure SSO uses Azure AD as the identity provider (IdP) to authenticate users. The authentication flow varies based on the authentication protocol used:

    1️⃣ SAML-based SSO – Azure AD sends a SAML token to authenticate the user.
    2️⃣ OAuth 2.0 / OpenID Connect (OIDC) – The user is authenticated via an authorization token.
    3️⃣ Password-based SSO – Azure AD stores credentials and auto-fills login fields for legacy apps.
    4️⃣ Linked-based SSO – Redirects users to a third-party identity provider for authentication.


    πŸ”Ή Implementing Azure SSO Using PowerShell

    Step 1: Prerequisites

    Before configuring SSO, ensure:
    βœ… You have Global Admin or Application Administrator role in Azure AD.
    βœ… The application supports SAML, OAuth, or OIDC.
    βœ… Azure AD Premium P1/P2 is available for Conditional Access policies (optional).
    βœ… You have PowerShell with AzureAD Module installed.

    To install the AzureAD module, run:

    powershellCopyEditInstall-Module AzureAD -Force -AllowClobber
    

    Connect to Azure AD:

    powershellCopyEditConnect-AzureAD
    

    Step 2: Register an Application in Azure AD

    To enable SSO, register the app in Azure AD.

    Using PowerShell

    1️⃣ Create the App Registration:

    powershellCopyEdit$AppName = "MyAzureSSOApp"
    $App = New-AzureADApplication -DisplayName $AppName
    $AppId = $App.AppId
    

    2️⃣ Create a Service Principal for the App:

    powershellCopyEditNew-AzureADServicePrincipal -AppId $AppId
    

    3️⃣ Assign Required Permissions (Example: Graph API)

    powershellCopyEdit$Permission = "User.Read.All"
    $AppRole = Get-AzureADServicePrincipal -Filter "AppId eq '$AppId'"
    New-AzureADServiceAppRoleAssignment -ObjectId $AppRole.ObjectId -PrincipalId $AppRole.ObjectId -ResourceId $AppRole.ObjectId -Id $Permission
    

    Step 3: Configure SSO for a SAML-based App

    1️⃣ Enable SAML SSO

    • Go to Azure AD > Enterprise Applications > Select App > Single sign-on
    • Choose SAML
    • Set Identifier (Entity ID) and Reply URL (Assertion Consumer Service URL) provided by the app.
    • Download Azure AD Federation Metadata XML and provide it to the app vendor.

    2️⃣ Configure User Attributes & Claims

    powershellCopyEditSet-AzureADServicePrincipal -ObjectId $AppRole.ObjectId -Saml2TokenIssuerName "https://login.microsoftonline.com/{tenant_id}/v2.0"
    

    3️⃣ Assign Users or Groups to the App

    powershellCopyEdit$User = Get-AzureADUser -ObjectId "[email protected]"
    Add-AzureADUserAppRoleAssignment -ObjectId $User.ObjectId -PrincipalId $AppRole.ObjectId -ResourceId $AppRole.ObjectId
    

    πŸ”Ή Best Practices for Azure SSO

    βœ” Use Conditional Access Policies – Require MFA for risky sign-ins.
    βœ” Enforce Role-Based Access Control (RBAC) – Assign least privilege access.
    βœ” Use Azure AD Identity Protection – Detect and mitigate suspicious activities.
    βœ” Regularly Review Application Permissions – Ensure only necessary apps have access.
    βœ” Enable SSO Logging and Monitoring – Track authentication attempts in Azure AD Sign-in Logs.


    πŸ”Ή Testing & Troubleshooting SSO

    After setup, test SSO via MyApps (https://myapps.microsoft.com) or direct application login.

    Common Fixes:

    πŸ”Ή Incorrect Reply URL? Ensure the correct Assertion Consumer Service (ACS) URL is set.
    πŸ”Ή User Not Assigned? Assign users or groups to the application.
    πŸ”Ή Invalid SAML Assertion? Check SAML response in Azure AD Sign-in Logs.
    πŸ”Ή SSO Failing for On-Prem Apps? Ensure Azure AD Connect is properly configured.


    πŸ”Ή Conclusion

    Azure SSO simplifies authentication, enhances security, and streamlines user access to applications. With Azure AD and PowerShell, you can automate SSO setup, manage user permissions, and enforce security best practices.

    πŸš€ Next Steps:
    βœ… Test your SSO setup and monitor sign-in logs.
    βœ… Apply Conditional Access policies for better security.
    βœ… Integrate more apps to provide a seamless user experience.

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

error: Content is protected !!