Author: jetnmariano

  • How to Identify Entra IDs with MS Authenticator Enabled in Azure

    As organizations embrace security best practices, enabling Multi-Factor Authentication (MFA) has become a critical requirement for securing access to applications and services. Microsoft provides multiple methods for MFA, one of the most commonly used being the Microsoft Authenticator app.

    In this blog, we’ll walk through how to identify how many Entra IDs have MS Authenticator enabled within your Azure Active Directory environment.

    Why is MS Authenticator Important?

    Microsoft Authenticator is an application that generates time-based one-time passcodes (TOTP) and pushes notifications for authentication requests. It’s part of the MFA process, adding an additional layer of protection beyond just passwords. Enabling MS Authenticator for users ensures a higher level of security, especially against phishing, password spraying, and other types of cyber attacks.

    Why Automate Identifying Entra IDs with MS Authenticator?

    By automating the process of identifying users who have MS Authenticator enabled, administrators can:

    1. Monitor MFA Adoption: Ensure that users are leveraging multi-factor authentication.
    2. Compliance and Security Auditing: Stay compliant with organizational or regulatory security requirements.
    3. Troubleshooting and Reporting: Quickly identify and resolve MFA-related login issues.

    The PowerShell Command to Identify Entra IDs with MS Authenticator

    To identify Entra IDs that are using MS Authenticator for MFA, we will use PowerShell commands with either the AzureAD or MSOnline module.

    Below are the two methods for identifying Entra IDs with MS Authenticator enabled:

    Steps to List Users with MS Authenticator Enabled:

    1. Install and Import the MSOnline Module (if not already done):

    powershellCopyInstall-Module -Name MSOnline
    Import-Module MSOnline
    

    2. Connect to Your MSOnline Instance:

    powershellCopyConnect-MsolService
    

    3. Run the Following Script to List Users with MS Authenticator Enabled:

    $usersWithMFA = Get-MsolUser -All | Where-Object { 
    $_.StrongAuthenticationMethods -ne $null -and
    $_.BlockCredential -eq $false
    }

    $usersWithMFA | Select DisplayName, UserPrincipalName, StrongAuthenticationMethods


    Explanation:

    1. Install and Import the MSOnline Module: This step ensures that the MSOnline module is available on your machine. If it’s already installed, the Import-Module command will load it into your session.
    2. Connect to MSOnline: This command establishes a connection to your Microsoft Online Services instance using your credentials.
    3. Script for Users with MS Authenticator Enabled: The PowerShell script filters out any blocked users ($_.BlockCredential -eq $false) and checks if they have either MobileAppNotification or MobileAppOTP as their strong authentication methods. These are the methods used by Microsoft Authenticator.
    4. Display the Results: The command at the end, $usersWithMSAuth | Select DisplayName, UserPrincipalName, filters out and displays the user’s display name and their principal name.

    alternate script to get users with MS Authenticator enabled.

    Conclusion

    Identifying users with MS Authenticator enabled is an essential part of ensuring the security of your Azure AD environment. By automating this process with PowerShell, you can keep track of your organization’s MFA adoption, improve compliance, and ensure that users have the best security practices in place.

    By regularly reviewing and automating this process, you will be able to improve security while keeping your environment streamlined and efficient.

  • Why Automating User MFA Reporting in Entra ID is Essential for Your Organization

    In today’s rapidly evolving cybersecurity landscape, Multi-Factor Authentication (MFA) plays a pivotal role in securing user access to critical systems and data. While Azure Active Directory (now Entra ID) provides a robust and comprehensive MFA solution, ensuring that users are using the right authentication methods and tracking that data can be time-consuming without proper automation.

    In this blog, we’ll explore what it means to identify users with phone-based MFA in Entra ID, why it’s important to automate this process, and how using PowerShell can significantly streamline the task.


    Understanding Phone-based MFA in Entra ID

    Phone-based MFA refers to the method of using a mobile phone or a phone number to authenticate users trying to access applications, services, or systems in Entra ID. This typically involves one of two methods:

    • Phone App Notification: The user receives a push notification to their phone and must approve or deny the login attempt.
    • Phone App OTP (One-Time Password): The user receives a temporary code (OTP) on their phone, which they must enter to complete the authentication.

    While these are robust forms of authentication, not every user within an organization will necessarily have phone-based MFA set up. Additionally, some users may be using alternate authentication methods, such as hardware tokens or biometrics, while others may have not configured any form of MFA at all.

    Based on my experience, phone-based MFA can cause issues with cross-tenant synchronization. Specifically, users who have phone-based MFA set up may face challenges in being provisioned to other tenants. The “NotInScope” and “NotEffectivelyEntitled” errors are often encountered during cross-tenant sync, preventing the proper provisioning of these users. This can cause delays and disrupt workflows, highlighting the importance of understanding and monitoring the MFA configurations of users across tenants.

    Why Track Active Users with Phone-based MFA?

    Ensuring that the right users are utilizing MFA, especially phone-based methods, is a key component of maintaining a secure environment. Here are a few reasons why tracking active users with phone-based MFA is crucial for your organization:

    1. Enhanced Security: With the rise of phishing attacks and data breaches, enforcing MFA provides an additional layer of security, ensuring that even if a user’s password is compromised, unauthorized access is still blocked. Phone-based MFA is one of the most secure forms of two-factor authentication.
    2. Compliance: Many organizations are bound by regulatory requirements, such as GDPR or HIPAA, that mandate MFA for accessing sensitive data. By ensuring that active users have MFA set up, especially phone-based methods, you can stay compliant with industry standards.
    3. User Experience: Simplified user access can lead to fewer friction points in daily workflows. With phone-based MFA, users can easily authenticate themselves without needing complicated hardware setups. Tracking and reporting on these users ensures that your organization stays on top of who’s set up and using MFA.
    4. Auditing and Reporting: Having visibility into the MFA status of your users is important for security auditing. Automated reporting ensures you’re not missing any critical configurations, and it can highlight any gaps that need addressing.
    5. Efficiency: Manual checks for MFA statuses and configurations can be tedious, especially for larger organizations with hundreds or thousands of users. By automating this process, you free up time for other essential tasks.

    Automating the MFA Reporting Process in Entra ID

    Manual auditing of MFA configurations can be error-prone, especially when done across large environments with multiple users. Automating the process not only improves accuracy but also ensures that the task is completed consistently.

    PowerShell provides a simple yet powerful solution for automating the reporting of active users who have phone-based MFA enabled in Entra ID. Here is how you can automate this process using PowerShell:

    Using the AzureAD Module:

    powershellCopy# Connect to Azure AD
    Connect-AzureAD
    
    # Get the list of active users with phone-based MFA enabled
    $usersWithPhoneMFA = Get-AzureADUser -All $true | 
        Where-Object {
            $_.AccountEnabled -eq $true -and
            (Get-AzureADUserMFA -ObjectId $_.ObjectId).Methods |
            Where-Object { $_.MethodType -eq "PhoneAppNotification" -or $_.MethodType -eq "PhoneAppOTP" }
        }
    
    # Display the users
    $usersWithPhoneMFA | Select DisplayName, UserPrincipalName
    

    Using the MSOnline Module:

    powershellCopy# Connect to MSOnline Connect-MsolService # Get the list of active users with phone-based MFA enabled $usersWithPhoneMFA = Get-MsolUser -All | Where-Object { $_.BlockCredential -eq $false -and ( $_.StrongAuthenticationMethods.MethodType -eq "PhoneAppNotification" -or $_.StrongAuthenticationMethods.MethodType -eq "PhoneAppOTP" ) } # Display the users $usersWithPhoneMFA | Select DisplayName, UserPrincipalName


    Why Automate This Process?

    Automating the reporting of active users with phone-based MFA brings a multitude of benefits:

    • Time-Saving: Automation allows you to quickly run reports and receive accurate information, which can otherwise take hours when done manually.
    • Real-Time Visibility: With automation, you get updated data at any time, helping you respond to potential security risks in real-time.
    • Scalability: Whether you have 10 or 10,000 users, automation ensures that the process scales to match your organization’s size without increasing the workload.
    • Accuracy: The automation removes the risk of human error, ensuring that the right users are being reported and that configurations are accurate.

    Conclusion

    Tracking active users with phone-based MFA is essential to maintaining security and compliance within your organization. By automating this process with PowerShell, you can save valuable time, improve reporting accuracy, and make better, data-driven decisions regarding your organization’s security posture.

    Automating these tasks also prepares your organization to scale efficiently and ensures that all users are adhering to the security standards you’ve set.

    If you haven’t yet automated your MFA reporting process, consider implementing a PowerShell solution and integrate it into your IT operations today. It’s a small investment that will yield significant improvements in both security and efficiency.

  • Monitor Windows Servers and Workstations Using PowerShell: Save Money on APM Tools

    Introduction

    In IT environments, keeping track of server health is critical to ensuring performance and avoiding downtime. Many organizations use Application Performance Monitoring (APM) tools such as SolarWinds, Datadog, or New Relic to monitor resources like CPU, RAM, and disk space usage.

    However, these tools can be costly. If you are looking for a cost-effective alternative, you can use PowerShell scripts to monitor system resources on your Windows Servers or Windows 10 workstations.

    This blog provides a PowerShell-based monitoring solution, eliminating the need for expensive software.


    Prerequisites

    Before running the script, make sure:

    • Your user account has administrative privileges on the target machines.
    • WinRM (Windows Remote Management) is enabled on the servers.
      • Run this on the target machines:powershellCopyEditEnable-PSRemoting -Force
    • PowerShell Execution Policy allows remote scripts.
      • Run this on your machine:powershellCopyEditSet-ExecutionPolicy RemoteSigned -Scope Process

    PowerShell Script to Monitor Windows Server Health

    This script collects CPU, RAM, and Disk usage from multiple servers and exports the data to a CSV file for reporting.

    powershellCopyEdit# List of servers to monitor (Modify as needed)
    $Servers = @("Server1", "Server2", "Server3")
    
    # Get current date for report file
    $Date = Get-Date -Format "yyyy-MM-dd"
    
    # Output file path
    $OutputFile = "C:\ServerReports\ServerHealthReport_$Date.csv"
    
    # Initialize an array to store results
    $Results = @()
    
    # Loop through each server
    foreach ($Server in $Servers) {
        if (Test-Connection -ComputerName $Server -Count 2 -Quiet) {
            # Get CPU usage
            $CPU = Get-WmiObject Win32_Processor -ComputerName $Server | Measure-Object -Property LoadPercentage -Average | Select-Object -ExpandProperty Average
    
            # Get RAM usage
            $RAM = Get-WmiObject Win32_OperatingSystem -ComputerName $Server
            $TotalRAM = [math]::Round($RAM.TotalVisibleMemorySize / 1MB, 2)
            $FreeRAM = [math]::Round($RAM.FreePhysicalMemory / 1MB, 2)
            $UsedRAM = $TotalRAM - $FreeRAM
            $RAMUsage = [math]::Round(($UsedRAM / $TotalRAM) * 100, 2)
    
            # Get Disk usage
            $Disk = Get-WmiObject Win32_LogicalDisk -ComputerName $Server -Filter "DeviceID='C:'"
            $TotalDisk = [math]::Round($Disk.Size / 1GB, 2)
            $FreeDisk = [math]::Round($Disk.FreeSpace / 1GB, 2)
            $UsedDisk = $TotalDisk - $FreeDisk
            $DiskUsage = [math]::Round(($UsedDisk / $TotalDisk) * 100, 2)
    
            # Store results in an object
            $Result = [PSCustomObject]@{
                ServerName  = $Server
                CPU_Usage   = "$CPU%"
                Total_RAM   = "$TotalRAM GB"
                Used_RAM    = "$UsedRAM GB"
                RAM_Usage   = "$RAMUsage%"
                Total_Disk  = "$TotalDisk GB"
                Used_Disk   = "$UsedDisk GB"
                Disk_Usage  = "$DiskUsage%"
            }
            
            # Add result to array
            $Results += $Result
        } else {
            Write-Host "$Server is unreachable." -ForegroundColor Red
        }
    }
    
    # Export results to CSV
    $Results | Export-Csv -Path $OutputFile -NoTypeInformation
    
    Write-Host "Server health report generated: $OutputFile" -ForegroundColor Green
    

    How This Script Works

    • Loops through the list of servers
    • Checks connectivity before querying each machine
    • Collects CPU, RAM, and Disk space usage
    • Formats the data for easy reading
    • Exports the results to a CSV file for reporting

    Automating the Script

    To run this script daily, use Task Scheduler:

    1. Open Task Scheduler and create a new task.
    2. Set the Trigger to run Daily at a specified time.
    3. In the Action tab, select:
      • Program/script: powershell.exe
      • Arguments:powershellCopyEdit-ExecutionPolicy Bypass -File "C:\Scripts\MonitorServers.ps1"
    4. Save the task.

    Conclusion

    • Avoid expensive APM software by using this PowerShell-based solution.
    • Schedule the script to run automatically and generate daily reports.
    • Works on Windows Servers and Windows 10 workstations.
    • Customizable: Add more resources (e.g., network usage, event logs) as needed.

    πŸš€ Want to improve this? Let me know in the comments!


    Stay tuned for more PowerShell automation guides!

    πŸš€ Follow for more IT solutions, automation scripts, and best practices!

  • How to Fix RDP NLA (Network Level Authentication) Error Using PowerShell

    Introduction

    Network Level Authentication (NLA) is a security feature in Remote Desktop Protocol (RDP) that requires authentication before establishing a session. While NLA enhances security, it can sometimes cause login issues, preventing users from connecting to a remote machine.

    This blog explains:

    • What causes the RDP NLA error
    • How to disable or enable NLA using PowerShell
    • Troubleshooting common NLA-related issues

    What Causes the RDP NLA Error?

    The NLA error typically occurs when:
    ❌ The remote machine cannot authenticate the user due to domain or credential issues.
    ❌ The remote machine is not part of a domain but still requires NLA.
    ❌ The remote machine’s security policy enforces NLA, preventing connections from unauthorized clients.
    ❌ The Remote Desktop Services are misconfigured.

    Error Message Example:

    “The remote computer requires Network Level Authentication (NLA), but your domain controller cannot be contacted to perform NLA. You must disable NLA on the remote computer in order to connect.”


    Fixing RDP NLA Errors Using PowerShell

    1️⃣ Temporarily Disable NLA via PowerShell

    If you cannot log in remotely, you may need to disable NLA from another computer that has admin access to the remote machine.

    Run this command in PowerShell (Admin Mode):

    powershellCopyEdit$RemoteComputer = "RemotePCName"
    
    Invoke-Command -ComputerName $RemoteComputer -ScriptBlock {
        Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -Name "UserAuthentication" -Value 0
        Restart-Service TermService -Force
    }
    
    Write-Host "NLA has been disabled on $RemoteComputer. Try connecting again." -ForegroundColor Green
    

    βœ… This command disables NLA and restarts the Remote Desktop Services (TermService).


    2️⃣ Disable NLA Locally (If You Have Local Access)

    If you can physically access the machine, use this PowerShell command:

    powershellCopyEditSet-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -Name "UserAuthentication" -Value 0
    Restart-Service TermService -Force
    Write-Host "NLA has been disabled. You can now RDP without NLA requirements." -ForegroundColor Green
    

    3️⃣ Enable NLA Again for Security

    Once you resolve the issue, re-enable NLA to restore security:

    powershellCopyEditSet-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -Name "UserAuthentication" -Value 1
    Restart-Service TermService -Force
    Write-Host "NLA has been enabled for improved security." -ForegroundColor Green
    

    βœ… This ensures only authenticated users can establish an RDP session.


    Additional Troubleshooting Steps

    βœ… Ensure Remote Desktop Services Are Running

    Run this command to check RDP services:

    powershellCopyEditGet-Service -Name TermService
    

    If it’s stopped, restart it:

    powershellCopyEditRestart-Service -Name TermService -Force
    

    βœ… Check Firewall Settings for RDP

    If RDP is blocked, allow it with:

    powershellCopyEditEnable-NetFirewallRule -DisplayGroup "Remote Desktop"
    Write-Host "Firewall rules updated. RDP is now allowed." -ForegroundColor Green
    

    βœ… Verify Domain Connectivity

    If the computer is domain-joined, ensure it can reach the domain controller:

    powershellCopyEditTest-ComputerSecureChannel -Server "YourDomainController" -Credential (Get-Credential)
    

    If it’s broken, repair it:

    powershellCopyEditReset-ComputerMachinePassword -Credential (Get-Credential)
    

    Best Practices to Avoid RDP NLA Errors

    βœ… Keep Remote Desktop Services and Windows Updates current.
    βœ… Ensure that all RDP clients support NLA (older clients may not).
    βœ… Configure Group Policy to allow fallback connections if needed:

    powershellCopyEditgpedit.msc
    

    Navigate to:
    Computer Configuration > Administrative Templates > Windows Components > Remote Desktop Services > Remote Desktop Session Host > Security
    Set Require user authentication for remote connections using NLA to Disabled (if troubleshooting).


    Conclusion

    The RDP NLA error is a security feature, but when misconfigured, it can block remote access. PowerShell provides an easy way to disable or enable NLA, restart RDP services, and troubleshoot connectivity issues.

    πŸš€ Did this guide help you? Let me know in the comments!

  • Clearing Your Browser Cache: A Complete Guide to Fixing Loading Issues

    Introduction

    Ever visited a website and noticed that it’s not updating or displaying incorrectly? This could be due to cached data stored in your browser. Browser caching is designed to speed up browsing by storing copies of web pages, images, and scripts, but sometimes it can cause problems by serving outdated content. Clearing your browser cache can fix issues like broken layouts, login errors, and pages not updating properly.

    In this guide, we’ll explore different methods to clear your browser cache across major browsers, including Google Chrome, Microsoft Edge, Mozilla Firefox, and Safari.


    Why Should You Clear Your Browser Cache?

    Here are some common reasons to clear your cache:

    • Fix loading or formatting issues (broken images, missing elements, or outdated content).
    • Resolve login problems (especially when credentials don’t update).
    • Ensure you’re viewing the latest website content (great for developers or website owners).
    • Improve browser performance by removing old data.
    • Fix issues after updating your website (WordPress users often experience caching problems).

    How to Clear Cache in Different Browsers

    1. Google Chrome (Windows & Mac)

    Method 1: Using Keyboard Shortcut (Quickest Way)

    1. Press Ctrl + Shift + Delete (Windows) or Cmd + Shift + Delete (Mac).
    2. A pop-up window will appear titled “Clear browsing data.”
    3. Select “Cached images and files” (you can also check cookies if needed).
    4. Choose Time Range: Select “All time” for a complete reset.
    5. Click “Clear data” and restart your browser.

    Method 2: Manually via Settings

    1. Click the three-dot menu in the top-right corner.
    2. Go to Settings > Privacy and Security.
    3. Click “Clear browsing data.”
    4. Follow the steps mentioned in Method 1 above.

    Method 3: Force Refresh Without Clearing Cache

    If you want to check a website for updates without clearing all cache:

    • Windows/Linux: Press Ctrl + F5 or Shift + F5.
    • Mac: Press Cmd + Shift + R.

    2. Mozilla Firefox (Windows & Mac)

    Method 1: Keyboard Shortcut

    1. Press Ctrl + Shift + Delete (Windows) or Cmd + Shift + Delete (Mac).
    2. Select “Cache” from the options.
    3. Choose “Everything” as the time range.
    4. Click “Clear Now” and restart Firefox.

    Method 2: Clearing Cache Manually

    1. Click the three-line menu (☰) in the top-right.
    2. Go to Settings > Privacy & Security.
    3. Scroll down to Cookies and Site Data and click “Clear Data.”
    4. Select “Cached Web Content” and clear it.

    Method 3: Hard Refresh (Force Reload)

    • Windows: Press Ctrl + Shift + R.
    • Mac: Press Cmd + Shift + R.

    3. Microsoft Edge (Windows)

    Method 1: Using Keyboard Shortcut

    1. Press Ctrl + Shift + Delete.
    2. Check “Cached images and files.”
    3. Select “All time” as the time range.
    4. Click “Clear now” and restart Edge.

    Method 2: Clearing Cache from Settings

    1. Click the three-dot menu in the top-right.
    2. Go to Settings > Privacy, search, and services.
    3. Under “Clear browsing data,” click “Choose what to clear.”
    4. Select “Cached images and files” and clear.

    Method 3: Hard Refresh

    • Windows: Press Ctrl + F5.

    4. Safari (Mac)

    Method 1: Clear Cache from Preferences

    1. Open Safari and click “Safari” > “Preferences.”
    2. Go to the “Advanced” tab and check “Show Develop menu in menu bar.”
    3. Close Preferences and click “Develop” > “Empty Caches.”
    4. Restart Safari.

    Method 2: Clearing Full Browsing History

    1. Click “Safari” > “Clear History.”
    2. Select “All history” and confirm.

    Method 3: Hard Refresh

    • Mac: Press Cmd + Option + R.

    Additional Fixes If Clearing Cache Doesn’t Work

    Sometimes clearing the cache alone isn’t enough. Here are a few extra troubleshooting steps:

    1. Try Incognito/Private Mode

    If a website is still not updating, open an Incognito or Private window and check if the issue persists.

    • Chrome/Edge: Ctrl + Shift + N
    • Firefox/Safari: Ctrl + Shift + P

    2. Disable Browser Extensions

    Some extensions (like ad blockers or privacy tools) may interfere with website functionality. Temporarily disable them and test the site.

    3. Flush DNS Cache

    If a website isn’t loading correctly, try flushing your computer’s DNS cache:

    • Windows: Open Command Prompt and run:powershellCopyEditipconfig /flushdns
    • Mac: Open Terminal and run:bashCopyEditsudo killall -HUP mDNSResponder

    4. Restart Your Device

    If nothing works, restart your browser or reboot your computer to apply the changes fully.


    Conclusion

    Clearing your browser cache is a simple yet effective way to fix many browsing issues. Whether you’re troubleshooting website errors, login problems, or just ensuring you’re viewing the latest updates, the methods above will help you clear cache effectively in any browser. If problems persist, consider advanced fixes like disabling extensions, flushing DNS, or restarting your system.

    Got any additional troubleshooting tips? Let us know in the comments!

    SharePoint Online: A Comprehensive Guide to Migration, Site Creation, Collaboration, and Permissions Management

    Introduction to SharePoint Online

    SharePoint Online is a cloud-based collaboration platform within Microsoft 365 that enables organizations to store, share, and manage content efficiently. It provides a centralized hub for document management, team collaboration, and business process automation. Unlike traditional on-premises SharePoint, SharePoint Online eliminates infrastructure maintenance, offering scalability, security, and integration with Microsoft tools like OneDrive, Teams, and Power Automate.

    This blog will cover:

    • Migrating on-premises data to SharePoint Online
    • Creating a SharePoint site
    • Collaborating effectively using SharePoint
    • Managing permissions for users and groups with best practices

    Migrating On-Premises Data to SharePoint Online

    Migrating from SharePoint Server (on-premises) to SharePoint Online requires careful planning. Below are the key steps:

    1. Pre-Migration Preparation

    • Inventory Assessment: Identify all files, libraries, and sites to be migrated.
    • Data Cleanup: Remove obsolete or duplicate files to optimize migration.
    • User Communication: Inform users about the migration timeline and expected changes.
    • Permissions Audit: Document current permissions and review what needs to be retained.

    2. Choosing a Migration Method

    There are multiple ways to migrate data:

    1. SharePoint Migration Tool (SPMT) – Best for small to medium-sized migrations.
    2. Microsoft FastTrack – Ideal for large-scale migrations with Microsoft-assisted guidance.
    3. Third-Party Tools – Tools like ShareGate, AvePoint, and Metalogix offer more flexibility.
    4. PowerShell – For advanced migration needs using Move-SPFile and Import-SPWeb commands.

    3. Performing the Migration

    • Using SharePoint Migration Tool (SPMT):
      1. Download and install the SPMT.
      2. Launch SPMT and sign in with Microsoft 365 credentials.
      3. Select Source (on-prem file share or SharePoint Server) and Destination (SharePoint Online site).
      4. Configure migration settings (permissions, metadata, version history).
      5. Start migration and monitor progress.
    • PowerShell Migration Example:powershellCopyEditStart-SPMTMigration -ImportPath "C:\SPMigration\manifest.json" -TenantName "yourtenant.sharepoint.com"

    4. Post-Migration Validation

    • Verify data integrity, permissions, and metadata.
    • Inform users of any changes and provide training if necessary.

    How to Create a SharePoint Online Site

    Creating a site in SharePoint Online allows teams to collaborate, store documents, and manage projects.

    1. Steps to Create a Site

    1. Go to SharePoint Online (via Microsoft 365 Portal).
    2. Click “Create site”.
    3. Choose a site type:
      • Team Site (for collaboration with Microsoft Teams integration).
      • Communication Site (for broad announcements and content sharing).
    4. Configure settings:
      • Enter site name and description.
      • Select privacy settings (Public or Private).
      • Assign owners and members.
    5. Click Finish, and the site is ready.

    2. Customizing the Site

    • Add document libraries and lists for structured content.
    • Create pages and news posts to share updates.
    • Enable versioning for document tracking.
    • Integrate Power Automate for workflows.

    How to Collaborate in SharePoint Online

    1. Document Management

    • Upload files to document libraries for centralized storage.
    • Use OneDrive Sync to work on files offline.
    • Enable co-authoring for real-time editing in Word, Excel, and PowerPoint.

    2. Communication and Sharing

    • Share files with internal or external users via direct links.
    • Use Microsoft Teams integration for instant collaboration.
    • Create news posts to keep users updated.

    3. Workflow Automation

    • Automate approvals and notifications using Power Automate.
    • Use Microsoft Lists for tracking tasks and issues.

    Understanding SharePoint Online Permissions

    Permissions in SharePoint Online control who can access, edit, and manage content. Poor permission management can lead to security risks and inefficiencies.

    1. Permission Levels in SharePoint

    SharePoint provides built-in permission levels:

    • Full Control – Manage everything in the site.
    • Edit – Add, edit, and delete items.
    • Contribute – Add and edit items but not delete them.
    • Read – View content only.
    • Restricted View – Can view but not download files.

    2. Managing Permissions for Users and Groups

    • Assign permissions at site, library, or item level.
    • Use Microsoft 365 Groups for simplified permission management.
    • Avoid direct user assignmentsβ€”use SharePoint groups instead.

    3. Best Practices for Permission Management

    βœ… Follow the Principle of Least Privilege – Assign only the necessary permissions.
    βœ… Use Groups Instead of Individual Users – Easier to manage at scale.
    βœ… Avoid Breaking Inheritance – Keep permissions at the site level unless necessary.
    βœ… Regularly Review Permissions – Audit user access periodically.
    βœ… Enable External Sharing Controls – Prevent unauthorized data leaks.


    Conclusion

    SharePoint Online is a powerful platform for collaboration, document management, and business process automation. Migrating from an on-premises SharePoint environment requires careful planning, while site creation and permission management are crucial for security and efficient teamwork. Following best practices for collaboration and permissions ensures a secure and productive environment.

    Automating SharePoint Online Site Creation with PowerShell

    Introduction

    Creating SharePoint Online sites manually through the Microsoft 365 portal is efficient for small-scale needs. However, when deploying multiple sites across an organization or ensuring consistency in configurations, PowerShell automation becomes essential.

    This guide will show how to use PowerShell to:

    • Connect to SharePoint Online
    • Create a new SharePoint Team Site or Communication Site
    • Set permissions and assign users
    • Customize site settings

    Prerequisites

    Before running the PowerShell scripts, ensure you meet the following requirements:

    1. Install SharePoint Online PowerShell Module

    If you haven’t already installed the SharePoint Online Management Shell, run:

    powershellCopyEditInstall-Module -Name Microsoft.Online.SharePoint.PowerShell -Force -AllowClobber
    

    2. Connect to SharePoint Online

    To authenticate, use:

    powershellCopyEdit$AdminSiteURL = "https://yourtenant-admin.sharepoint.com"
    Connect-SPOService -Url $AdminSiteURL -Credential (Get-Credential)
    

    You’ll be prompted to enter your Microsoft 365 credentials.


    Creating a SharePoint Online Team Site

    A Team Site is used for collaboration, file sharing, and Microsoft Teams integration.

    PowerShell Script to Create a Team Site

    powershellCopyEdit# Define Variables
    $SiteURL = "https://yourtenant.sharepoint.com/sites/NewTeamSite"
    $SiteTitle = "New Team Site"
    $Owner = "[email protected]"
    $Template = "STS#3" # STS#3 is used for Modern Team Sites
    $StorageQuota = 2048
    
    # Create the Site
    New-SPOSite -Url $SiteURL -Owner $Owner -StorageQuota $StorageQuota -Title $SiteTitle -Template $Template
    
    Write-Host "SharePoint Online Team Site Created Successfully!" -ForegroundColor Green
    

    Explanation of Parameters

    • $SiteURL β†’ Defines the site URL.
    • $SiteTitle β†’ Name of the SharePoint site.
    • $Owner β†’ The primary administrator for the site.
    • $Template β†’ "STS#3" is used for modern team sites.
    • $StorageQuota β†’ Allocates 2GB (modify as needed).

    Creating a SharePoint Online Communication Site

    A Communication Site is used for sharing information broadly, such as for company news or an intranet.

    PowerShell Script to Create a Communication Site

    powershellCopyEdit# Define Variables
    $SiteURL = "https://yourtenant.sharepoint.com/sites/CompanyNews"
    $SiteTitle = "Company News"
    $Owner = "[email protected]"
    
    # Create the Communication Site
    New-SPOSite -Url $SiteURL -Owner $Owner -Title $SiteTitle -Template "SITEPAGEPUBLISHING#0"
    
    Write-Host "SharePoint Online Communication Site Created Successfully!" -ForegroundColor Green
    

    Template Reference

    • "SITEPAGEPUBLISHING#0" β†’ Used for Communication Sites.

    Assigning Permissions to SharePoint Online Sites

    Permissions are critical for defining who can view, edit, and manage the SharePoint site.

    Adding a User to the Site

    powershellCopyEdit$SiteURL = "https://yourtenant.sharepoint.com/sites/NewTeamSite"
    $UserEmail = "[email protected]"
    $GroupName = "Members"  # Options: Owners, Members, Visitors
    
    # Add User to SharePoint Site Group
    Add-SPOUser -Site $SiteURL -LoginName $UserEmail -Group $GroupName
    
    Write-Host "User added successfully to $GroupName" -ForegroundColor Green
    

    Granting Permissions Directly

    powershellCopyEditSet-SPOUser -Site $SiteURL -LoginName $UserEmail -IsSiteCollectionAdmin $true
    Write-Host "User has been granted site collection admin access." -ForegroundColor Green
    

    Modifying Storage Quotas for SharePoint Sites

    If you need to change the storage quota for an existing SharePoint site:

    powershellCopyEditSet-SPOSite -Identity $SiteURL -StorageQuota 5000
    Write-Host "Storage quota updated to 5GB." -ForegroundColor Green
    

    Automating Site Creation for Multiple Sites

    If you need to bulk create multiple SharePoint sites, use a CSV file.

    Step 1: Create a CSV File

    Save this as “SitesToCreate.csv”:

    perlCopyEditSiteURL,Title,Owner,Template
    https://yourtenant.sharepoint.com/sites/HR,HR Site,[email protected],STS#3
    https://yourtenant.sharepoint.com/sites/Finance,Finance Site,[email protected],SITEPAGEPUBLISHING#0
    

    Step 2: PowerShell Script to Bulk Create SharePoint Sites

    powershellCopyEdit$Sites = Import-Csv "C:\Path\To\SitesToCreate.csv"
    
    foreach ($Site in $Sites) {
        New-SPOSite -Url $Site.SiteURL -Owner $Site.Owner -Title $Site.Title -Template $Site.Template
        Write-Host "Created SharePoint Site: $($Site.Title)" -ForegroundColor Green
    }
    

    Best Practices for SharePoint Online Site Management

    βœ… Use Site Templates Consistently – Choose the right type of site (STS#3 for Team, SITEPAGEPUBLISHING#0 for Communication).
    βœ… Implement Governance Policies – Control who can create sites, set expiration policies, and define storage limits.
    βœ… Use Power Automate for Workflow Automation – Automate notifications, approvals, and document workflows.
    βœ… Regularly Audit Permissions – Ensure users have appropriate access without over-permissioning.
    βœ… Enable Multi-Factor Authentication (MFA) – Secure SharePoint access for administrators and users.


    Conclusion

    PowerShell is a powerful tool for automating SharePoint Online site creation, permissions, and management. Using these scripts, IT administrators can reduce manual workload, ensure consistency, and enhance security.

    Managing SharePoint Online Lists and Libraries with PowerShell

    Introduction

    SharePoint Online lists and libraries are essential tools for storing, organizing, and sharing data. While they can be managed through the UI, PowerShell automation provides greater flexibility and efficiency.

    This guide covers:

    • Creating SharePoint lists and libraries with PowerShell
    • Managing list columns, permissions, and views
    • Bulk importing data into SharePoint lists
    • Best practices for list and library management

    Prerequisites

    Before running the PowerShell scripts, ensure you have:

    1. SharePoint Online Management Shell installed:powershellCopyEditInstall-Module -Name Microsoft.Online.SharePoint.PowerShell -Force -AllowClobber
    2. Connected to SharePoint Online:powershellCopyEdit$AdminSiteURL = "https://yourtenant-admin.sharepoint.com" Connect-SPOService -Url $AdminSiteURL -Credential (Get-Credential)

    Creating a SharePoint Online List

    A list in SharePoint is used for storing structured data like tasks, contacts, or project tracking.

    PowerShell Script to Create a List

    powershellCopyEdit# Define Variables
    $SiteURL = "https://yourtenant.sharepoint.com/sites/YourSite"
    $ListTitle = "Project Tracker"
    $ListDescription = "This list tracks project progress"
    $TemplateType = "GenericList" # Options: GenericList, Contacts, Tasks, Announcements
    
    # Create the List
    Connect-PnPOnline -Url $SiteURL -UseWebLogin
    New-PnPList -Title $ListTitle -Template $TemplateType -Description $ListDescription -OnQuickLaunch
    
    Write-Host "SharePoint Online List '$ListTitle' Created Successfully!" -ForegroundColor Green
    

    Available List Templates

    Template NameType
    GenericListCustom List
    ContactsContacts List
    TasksTask List
    AnnouncementsAnnouncement List

    Adding Columns to a SharePoint List

    Columns define the type of data stored in the list.

    PowerShell Script to Add Columns

    powershellCopyEdit# Define Variables
    $Column1 = "Project Name"
    $Column2 = "Due Date"
    $Column3 = "Status"
    
    # Add Columns
    Add-PnPField -List $ListTitle -DisplayName $Column1 -InternalName "ProjectName" -Type Text
    Add-PnPField -List $ListTitle -DisplayName $Column2 -InternalName "DueDate" -Type DateTime
    Add-PnPField -List $ListTitle -DisplayName $Column3 -InternalName "Status" -Type Choice -Choices "Not Started", "In Progress", "Completed"
    
    Write-Host "Columns Added Successfully!" -ForegroundColor Green
    

    Creating a SharePoint Online Document Library

    A document library is used to store files and manage document collaboration.

    PowerShell Script to Create a Library

    powershellCopyEdit# Define Variables
    $LibraryTitle = "Project Documents"
    $LibraryDescription = "Library for storing project-related files"
    
    # Create the Library
    New-PnPList -Title $LibraryTitle -Template DocumentLibrary -Description $LibraryDescription -OnQuickLaunch
    
    Write-Host "Document Library '$LibraryTitle' Created Successfully!" -ForegroundColor Green
    

    Uploading Files to a Document Library

    To upload a file into a document library:

    powershellCopyEdit# Define Variables
    $LibraryName = "Project Documents"
    $FilePath = "C:\Users\YourUser\Desktop\SampleFile.pdf"
    $DestinationURL = "/sites/YourSite/$LibraryName"
    
    # Upload the File
    Add-PnPFile -Path $FilePath -Folder $DestinationURL
    
    Write-Host "File Uploaded Successfully!" -ForegroundColor Green
    

    Bulk Import Data into a SharePoint List

    If you have Excel or CSV data, you can bulk import it into SharePoint.

    Step 1: Create a CSV File

    Save as ProjectData.csv:

    mathematicaCopyEditProjectName,DueDate,Status
    Migration to Azure,2024-06-15,In Progress
    SharePoint Redesign,2024-07-01,Not Started
    Security Audit,2024-05-20,Completed
    

    Step 2: PowerShell Script to Import Data

    powershellCopyEdit# Import CSV
    $ListName = "Project Tracker"
    $CSVFile = "C:\Path\To\ProjectData.csv"
    $Data = Import-Csv -Path $CSVFile
    
    # Loop through each row and add to SharePoint list
    foreach ($Item in $Data) {
        Add-PnPListItem -List $ListName -Values @{
            "Project Name" = $Item.ProjectName
            "Due Date" = $Item.DueDate
            "Status" = $Item.Status
        }
    }
    
    Write-Host "Data Imported Successfully!" -ForegroundColor Green
    

    Managing SharePoint List Permissions

    You can restrict access to a list or library.

    Grant User Permissions

    powershellCopyEdit$UserEmail = "[email protected]"
    $Permission = "Contribute"
    
    Grant-PnPListPermissions -Identity $ListTitle -User $UserEmail -Role $Permission
    
    Write-Host "User granted $Permission access to the list." -ForegroundColor Green
    

    Remove User Permissions

    powershellCopyEditRevoke-PnPListPermissions -Identity $ListTitle -User $UserEmail
    Write-Host "User removed from the list." -ForegroundColor Green
    

    Deleting a SharePoint List or Library

    To delete a list:

    powershellCopyEditRemove-PnPList -Identity $ListTitle -Force
    Write-Host "List Deleted Successfully!" -ForegroundColor Red
    

    To delete a document library:

    powershellCopyEditRemove-PnPList -Identity $LibraryTitle -Force
    Write-Host "Library Deleted Successfully!" -ForegroundColor Red
    

    Best Practices for Managing SharePoint Lists & Libraries

    βœ… Use Managed Metadata – Standardize data entry and improve searchability.
    βœ… Enable Versioning – Keep track of document changes in libraries.
    βœ… Restrict Permissions – Assign the least privilege access necessary.
    βœ… Automate Workflows – Use Power Automate to notify users when items are updated.
    βœ… Regularly Audit Lists – Remove outdated lists and optimize storage.


    Conclusion

    By leveraging PowerShell, SharePoint Online lists and libraries can be automated, secured, and optimized. Whether you are managing user permissions, bulk importing data, or creating document libraries, these scripts will enhance your efficiency.

    Managing SharePoint Online Retention Policies and Compliance with PowerShell

    Introduction

    Ensuring compliance and protecting critical business data is essential for every organization. Retention policies in SharePoint Online help safeguard information, prevent accidental deletion, and comply with legal and regulatory requirements.

    This blog covers:

    • Understanding SharePoint Retention Policies
    • Configuring retention labels and policies using PowerShell
    • Setting up audit logs to track changes
    • Best practices for SharePoint compliance management

    What Are SharePoint Online Retention Policies?

    Retention policies define how long data should be stored before deletion. Policies can: βœ… Retain content for a specified time
    βœ… Delete content automatically after a specific period
    βœ… Prevent permanent deletion of critical records

    Retention settings apply to:

    • SharePoint Sites
    • Document Libraries
    • Lists & Items
    • OneDrive for Business
    • Microsoft Teams Data (Files & Messages)

    Prerequisites

    Before configuring retention policies in SharePoint Online, ensure:

    1. You have Global Admin, Compliance Admin, or SharePoint Admin privileges.
    2. You have installed the PowerShell modules:powershellCopyEditInstall-Module ExchangeOnlineManagement -Scope CurrentUser Install-Module Microsoft.Graph -Scope CurrentUser
    3. Connect to Microsoft Compliance Center:powershellCopyEditConnect-IPPSSession

    Creating a SharePoint Online Retention Policy

    Retention policies can be created using PowerShell to automate policy enforcement.

    Step 1: Define the Retention Policy

    Set policy name, duration, and action (retain or delete).

    powershellCopyEdit$PolicyName = "Finance Retention Policy"
    $RetentionDays = 3650  # 10 years
    $Action = "Retain"  # Options: "Retain" or "Delete"
    
    New-RetentionCompliancePolicy -Name $PolicyName -RetentionDuration $RetentionDays -RetentionComplianceAction $Action
    
    Write-Host "Retention Policy '$PolicyName' Created Successfully!" -ForegroundColor Green
    

    Step 2: Apply the Policy to a SharePoint Site

    powershellCopyEdit$SiteURL = "https://yourtenant.sharepoint.com/sites/FinanceSite"
    Set-RetentionCompliancePolicy -Name $PolicyName -AddExchangeLocation $SiteURL
    
    Write-Host "Retention Policy Applied to $SiteURL" -ForegroundColor Green
    

    Creating Retention Labels for SharePoint Documents

    Retention labels classify and enforce retention actions on documents.

    Step 1: Create a Retention Label

    powershellCopyEdit$LabelName = "Confidential Documents"
    $RetentionPeriod = 1825  # 5 years
    
    New-RetentionComplianceRule -Name $LabelName -RetentionDuration $RetentionPeriod -RetentionComplianceAction "Retain"
    
    Write-Host "Retention Label '$LabelName' Created Successfully!" -ForegroundColor Green
    

    Step 2: Publish the Label to SharePoint

    powershellCopyEdit$PolicyName = "Confidential Retention"
    New-LabelPolicy -Name $PolicyName -Labels $LabelName -Sites "https://yourtenant.sharepoint.com/sites/Confidential"
    
    Write-Host "Retention Label Published to SharePoint Site" -ForegroundColor Green
    

    Enabling Auditing for SharePoint Compliance

    Auditing tracks user activity, such as file modifications, deletions, and access attempts.

    Enable Audit Logs via PowerShell

    powershellCopyEditSet-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true
    Write-Host "Unified Audit Log Enabled!" -ForegroundColor Green
    

    Retrieve and Export Audit Logs

    powershellCopyEditSearch-UnifiedAuditLog -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) -RecordType SharePointFileOperation -ResultSize 5000 | Export-Csv "C:\AuditLogs.csv" -NoTypeInformation
    
    Write-Host "Audit Logs Exported Successfully!" -ForegroundColor Green
    

    Best Practices for SharePoint Retention & Compliance

    βœ… Use retention labels instead of blanket retention policies for targeted control.
    βœ… Apply different policies based on department needs (e.g., Finance, HR, Legal).
    βœ… Monitor compliance using audit logs and adjust retention as needed.
    βœ… Educate users on document classification and retention requirements.
    βœ… Regularly review retention policies to align with business and regulatory changes.


    Conclusion

    Managing SharePoint Online retention policies ensures compliance, data security, and governance. Using PowerShell, IT admins can automate policy creation, apply retention labels, and monitor compliance efficiently.

  • What is SAML and How to Configure It?

    Introduction to SAML

    Security Assertion Markup Language (SAML) is an XML-based authentication standard used for Single Sign-On (SSO). It allows users to log in once and access multiple applications without entering credentials repeatedly.

    Why Use SAML?

    • Enhanced Security: SAML enables authentication via an identity provider (IdP) rather than storing credentials in multiple applications.
    • SSO Capabilities: Users only log in once to access different apps.
    • Interoperability: Works across various identity providers and service providers.

    How SAML Works

    1. User Requests Access: The user tries to access an application (Service Provider – SP).
    2. Redirect to Identity Provider (IdP): The user is redirected to the IdP for authentication.
    3. Authentication & Assertion: The IdP verifies credentials and sends a SAML assertion (authentication token) back.
    4. User Gains Access: The SP validates the assertion and grants access.

    How to Configure SAML Authentication in Entra ID

    To set up SAML-based authentication in Entra ID, follow these steps:

    Step 1: Register an Enterprise Application

    1. Go to Microsoft Entra ID in the Azure Portal.
    2. Navigate to Enterprise Applications > New Application.
    3. Select Non-gallery application and provide a name for your app.
    4. Click Create.

    Step 2: Configure Single Sign-On (SSO)

    1. In the newly created app, go to Single sign-on.
    2. Choose SAML as the authentication method.
    3. Configure the Basic SAML Configuration:
      • Identifier (Entity ID): https://yourapp.com
      • Reply URL (Assertion Consumer Service URL): https://yourapp.com/sso/callback
      • Sign-on URL: https://yourapp.com/login
    4. Click Save.

    Step 3: Download & Share SAML Metadata

    • Download the Federation Metadata XML from the SAML Signing Certificate section.
    • Provide this XML file to the Service Provider (SP) to complete the integration.

    Step 4: Assign Users to the Application

    1. Go to Users and Groups in the Enterprise Application.
    2. Assign users who should have access to the app.

    Step 5: Test SSO

    1. Click on Test SSO in the SAML settings.
    2. Ensure authentication is successful and users can log in.

    Configuring SAML in Entra ID Using PowerShell

    You can automate the setup using PowerShell with the Microsoft Graph API.

    Step 1: Connect to Microsoft Graph
    powershellCopyEditConnect-MgGraph -Scopes "Application.ReadWrite.All", "AppRoleAssignment.ReadWrite.All"
    
    Step 2: Register an Enterprise Application
    powershellCopyEdit$enterpriseApp = New-MgServicePrincipal -AppId "00000003-0000-0000-c000-000000000000"
    
    Step 3: Configure SAML SSO
    powershellCopyEdit$sp = Get-MgServicePrincipal -Filter "DisplayName eq 'YourAppName'"
    
    # Set SAML properties
    Update-MgServicePrincipal -ServicePrincipalId $sp.Id -PreferredTokenSigningKeyThumbprint "YourThumbprint"
    
    Step 4: Assign Users
    powershellCopyEdit$user = Get-MgUser -UserPrincipalName "[email protected]"
    New-MgUserAppRoleAssignment -UserId $user.Id -ResourceId $sp.Id -AppRoleId "Role ID"
    

    Conclusion

    SAML authentication provides a secure and efficient way for users to authenticate with multiple applications using a single sign-on (SSO) process. Configuring SAML in Microsoft Entra ID enhances security, simplifies user access, and integrates seamlessly with cloud-based applications.

    Entra ID App Registration – Introduction, Purpose, and PowerShell Guide

    Introduction

    Microsoft Entra ID (formerly known as Azure AD) is the identity and access management (IAM) solution for Microsoft cloud services. App registration in Entra ID is essential for integrating applications with Entra ID, enabling authentication and authorization for users and services.

    Purpose of Entra ID App Registration

    Entra ID App Registration allows developers and IT admins to:

    • Enable secure authentication for applications.
    • Configure permissions for Microsoft Graph and other APIs.
    • Use OAuth 2.0 and OpenID Connect for secure authentication.
    • Enable multi-tenant access for applications.

    By registering an app, you establish its identity with Entra ID, allowing it to authenticate users and access resources.


    Creating an Entra ID App Registration Using PowerShell

    To create an app registration in Entra ID using PowerShell, follow these steps:

    Prerequisites

    • You must have AzureAD or Microsoft.Graph PowerShell module installed.
    • You need Global Administrator or Application Administrator permissions.

    Steps to Create an App Registration Using PowerShell

    Step 1: Install and Connect to Microsoft Graph PowerShell
    powershellCopyEdit# Install the Microsoft Graph PowerShell module if not installed
    Install-Module Microsoft.Graph -Scope CurrentUser
    
    # Connect to Entra ID with the required permissions
    Connect-MgGraph -Scopes "Application.ReadWrite.All", "AppRoleAssignment.ReadWrite.All"
    
    Step 2: Create the App Registration
    powershellCopyEdit# Define the application name
    $appName = "MyEntraApp"
    
    # Register the application
    $app = New-MgApplication -DisplayName $appName
    
    # Output the app details
    $app
    
    Step 3: Create a Service Principal for the App
    powershellCopyEdit# Create a service principal to enable authentication for the app
    $sp = New-MgServicePrincipal -AppId $app.AppId
    
    # Output the service principal details
    $sp
    
    Step 4: Assign API Permissions
    powershellCopyEdit# Define API permissions
    $graphPermission = @{
        "resourceAppId" = "00000003-0000-0000-c000-000000000000" # Microsoft Graph
        "resourceAccess" = @(@{"id"="Role ID";"type"="Role"})  # Replace Role ID with the specific permission ID
    }
    
    # Assign permissions to the app
    Update-MgApplication -ApplicationId $app.Id -RequiredResourceAccess $graphPermission
    
    Step 5: Generate a Client Secret
    powershellCopyEdit# Create a client secret for the application
    $clientSecret = Add-MgApplicationPassword -ApplicationId $app.Id -DisplayName "MySecret"
    
    # Output client secret details
    $clientSecret
    
    Step 6: Retrieve the App Details
    powershellCopyEditWrite-Host "Application ID: $($app.AppId)"
    Write-Host "Service Principal ID: $($sp.Id)"
    Write-Host "Client Secret: $($clientSecret.SecretText) (Copy this as it won't be retrievable again!)"
    

    Conclusion

    By following these steps, you have successfully registered an application in Microsoft Entra ID using PowerShell. This setup allows your app to authenticate users, request API permissions, and securely interact with cloud resources.

  • Identifying Enabled Accounts in Azure Active Directory

    For Azure AD, use Microsoft Graph PowerShell.

    Step 1: Install & Connect to Azure AD

    powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
    Connect-MgGraph -Scopes "User.Read.All"
    

    Step 2: Retrieve Enabled Users from Azure AD

    powershellCopyEdit$AzureEnabledUsers = Get-MgUser -Filter "accountEnabled eq true" | 
        Select-Object DisplayName, UserPrincipalName, Mail, Id 
    
    $AzureEnabledUsers | Format-Table -AutoSize
    

    βœ… Filters only enabled accounts
    βœ… Displays key details (Display Name, UPN, Email, Object ID)


    πŸ”Ή Step 3: Export Azure AD Enabled Users to CSV

    powershellCopyEdit$AzureEnabledUsers | Export-Csv -Path "C:\Reports\AzureEnabledUsers.csv" -NoTypeInformation -Encoding UTF8
    

    πŸ“Œ Use this report for license management, compliance checks, and security audits.


    πŸ”Ή Automating the Process (Scheduled Task)

    To automate this script daily or weekly, set up a PowerShell scheduled task:

    1️⃣ Save the script as EnabledUsersReport.ps1
    2️⃣ Open Task Scheduler β†’ Create Basic Task
    3️⃣ Set Trigger (Daily, Weekly, etc.)
    4️⃣ Set Action β†’ Start a Program β†’ powershell.exe -File C:\Scripts\EnabledUsersReport.ps1
    5️⃣ Save & Run

    βœ… Now, you will get automated reports without manual effort! πŸš€


    πŸ”Ή Summary

    βœ… Enabled accounts must be regularly audited to maintain security & compliance.
    βœ… PowerShell simplifies the process of retrieving and exporting enabled accounts.
    βœ… On-Prem AD & Azure AD scripts ensure comprehensive user monitoring.
    βœ… Automating via scheduled tasks ensures continuous and hands-free monitoring.

    By implementing this automation, IT administrators can proactively identify security risks, optimize licensing, and ensure compliance.

    Automating the Disabling of Inactive Accounts in Active Directory & Azure AD Using PowerShell

    Introduction

    Inactive user accounts pose a serious security risk to any IT environment. Accounts that remain enabled but unused can be exploited by attackers, leading to potential data breaches, unauthorized access, and compliance violations.

    By automating the identification and disabling of inactive accounts in Active Directory (AD) and Azure AD, organizations can enhance security and reduce attack surfaces.

    This blog provides step-by-step PowerShell scripts to:
    βœ… Identify inactive accounts
    βœ… Disable inactive users automatically
    βœ… Export the results for auditing
    βœ… Schedule the task for continuous security


    πŸ”Ή Why Disable Inactive Accounts?

    πŸ“Œ Security – Reduce the risk of unauthorized access.
    πŸ“Œ Compliance – Align with industry regulations (ISO 27001, NIST, GDPR, HIPAA).
    πŸ“Œ License Optimization – Free up unused Microsoft 365 & Azure AD licenses.
    πŸ“Œ Operational Efficiency – Keep Active Directory clean and organized.

    Let’s automate this process using PowerShell. πŸš€


    πŸ”Ή Identifying & Disabling Inactive Accounts in On-Prem Active Directory

    In Active Directory, a user is considered inactive if they haven’t logged in for a specific period (e.g., 90 days).

    Step 1: Install & Import the Active Directory Module

    Ensure the AD module is installed before running the script:

    powershellCopyEditInstall-WindowsFeature -Name RSAT-AD-PowerShell
    Import-Module ActiveDirectory
    

    Step 2: Find Inactive Users (No Login for 90 Days)

    powershellCopyEdit$InactiveUsers = Get-ADUser -Filter {Enabled -eq $true} -Properties LastLogonDate | 
        Where-Object { $_.LastLogonDate -lt (Get-Date).AddDays(-90) } | 
        Select-Object DisplayName, SamAccountName, LastLogonDate, Enabled
    
    $InactiveUsers | Format-Table -AutoSize
    

    βœ… Retrieves all enabled users
    βœ… Filters users who haven’t logged in for 90+ days
    βœ… Displays Name, Username, Last Login Date


    πŸ”Ή Step 3: Disable Inactive Users

    powershellCopyEdit$InactiveUsers | ForEach-Object {
        Disable-ADUser -Identity $_.SamAccountName -Confirm:$false
    }
    Write-Host "Inactive accounts disabled successfully!" -ForegroundColor Green
    

    πŸ“Œ The accounts remain in AD but are disabled πŸ›‘


    πŸ”Ή Step 4: Export Disabled Users for Auditing

    powershellCopyEdit$InactiveUsers | Export-Csv -Path "C:\Reports\DisabledUsers.csv" -NoTypeInformation -Encoding UTF8
    

    πŸ“Œ Keeps a record of disabled accounts for auditing & rollback if needed


    πŸ”Ή Identifying & Disabling Inactive Users in Azure AD

    For Azure AD, user inactivity is determined based on the LastSignInDateTime attribute.

    Step 1: Install & Connect to Azure AD

    powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
    Connect-MgGraph -Scopes "User.ReadWrite.All"
    

    Step 2: Find Inactive Azure AD Users (90 Days of Inactivity)

    powershellCopyEdit$AzureInactiveUsers = Get-MgUser -Filter "accountEnabled eq true" -Property DisplayName,UserPrincipalName,SignInActivity | 
        Where-Object { $_.SignInActivity.LastSignInDateTime -lt (Get-Date).AddDays(-90) } | 
        Select-Object DisplayName, UserPrincipalName, SignInActivity.LastSignInDateTime
    
    $AzureInactiveUsers | Format-Table -AutoSize
    

    βœ… Retrieves all enabled users
    βœ… Filters users who haven’t signed in for 90+ days
    βœ… Displays Name, UPN, Last Sign-In Date


    πŸ”Ή Step 3: Disable Inactive Azure AD Users

    powershellCopyEdit$AzureInactiveUsers | ForEach-Object {
        Update-MgUser -UserId $_.UserPrincipalName -AccountEnabled:$false
    }
    Write-Host "Inactive Azure AD accounts disabled successfully!" -ForegroundColor Green
    

    πŸ“Œ Azure AD users are now disabled πŸ›‘


    πŸ”Ή Step 4: Export Disabled Azure AD Users for Auditing

    powershellCopyEdit$AzureInactiveUsers | Export-Csv -Path "C:\Reports\DisabledAzureUsers.csv" -NoTypeInformation -Encoding UTF8
    

    πŸ“Œ Retains a record for compliance and rollback purposes


    πŸ”Ή Automating the Process (Scheduled Task)

    To automate the process, create a PowerShell script and schedule it to run periodically.

    1️⃣ Save the script as DisableInactiveUsers.ps1
    2️⃣ Open Task Scheduler β†’ Create Basic Task
    3️⃣ Set Trigger (e.g., Weekly, Monthly)
    4️⃣ Set Action β†’ Start a Program β†’ powershell.exe -File C:\Scripts\DisableInactiveUsers.ps1
    5️⃣ Save & Run

    πŸ“Œ Now, the script will run automatically, disabling inactive users on schedule.


    πŸ”Ή Summary

    βœ… Inactive accounts are a security riskβ€”automate their disabling.
    βœ… PowerShell simplifies managing on-prem AD & Azure AD users.
    βœ… Exporting logs ensures compliance and rollback safety.
    βœ… Automating with Task Scheduler keeps environments secure without manual work.

    By implementing this automated approach, IT teams can enhance security, ensure compliance, and reduce riskβ€”all with PowerShell! πŸš€

    Re-Enabling Disabled Users in Azure AD

    For Azure AD, we need to use Microsoft Graph PowerShell.

    Step 1: Install & Connect to Azure AD

    powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
    Connect-MgGraph -Scopes "User.ReadWrite.All"
    

    Step 2: Find Disabled Users in Azure AD

    powershellCopyEdit$DisabledAzureUsers = Get-MgUser -Filter "accountEnabled eq false" -Property DisplayName, UserPrincipalName | 
        Select-Object DisplayName, UserPrincipalName
    
    $DisabledAzureUsers | Format-Table -AutoSize
    

    βœ… Lists all disabled users in Azure AD


    πŸ”Ή Step 3: Re-Enable Disabled Azure AD Users

    powershellCopyEdit$DisabledAzureUsers | ForEach-Object {
        Update-MgUser -UserId $_.UserPrincipalName -AccountEnabled:$true
    }
    Write-Host "All disabled Azure AD users have been re-enabled!" -ForegroundColor Green
    

    πŸ“Œ Azure AD users are now restored and can log in again πŸ”„


    πŸ”Ή Step 4: Export Re-Enabled Azure AD Users for Auditing

    powershellCopyEdit$DisabledAzureUsers | Export-Csv -Path "C:\Reports\ReEnabledAzureUsers.csv" -NoTypeInformation -Encoding UTF8
    

    πŸ“Œ Keeps an audit log of re-enabled accounts


    πŸ”Ή Automating the Re-Enablement Process (Scheduled Task)

    To automate the process, create a PowerShell script and schedule it to run periodically.

    1️⃣ Save the script as ReEnableUsers.ps1
    2️⃣ Open Task Scheduler β†’ Create Basic Task
    3️⃣ Set Trigger (e.g., Weekly, Monthly)
    4️⃣ Set Action β†’ Start a Program β†’ powershell.exe -File C:\Scripts\ReEnableUsers.ps1
    5️⃣ Save & Run

    πŸ“Œ Now, the script will run automatically, checking for and re-enabling disabled users.


    πŸ”Ή Summary

    βœ… Automating re-enablement helps streamline IT operations.
    βœ… PowerShell makes it easy to manage AD & Azure AD accounts.
    βœ… Exporting logs ensures accountability for security compliance.
    βœ… Task Scheduler keeps everything automated.

    By implementing this automated approach, IT teams can quickly restore access when needed, without manual work. πŸš€

    Automating User Notifications for Account Disablement & Re-Enablement Using PowerShell

    πŸ”Ή Introduction

    Managing user accounts effectively requires clear communication between IT and employees. When a user’s account is disabled or re-enabled, notifying them (or their manager) reduces confusion and improves security compliance.

    This blog provides PowerShell scripts to:
    βœ… Automatically notify users when their account is disabled
    βœ… Send alerts when accounts are re-enabled
    βœ… Email managers about account status changes
    βœ… Export logs for auditing


    πŸ”Ή Why Automate Account Status Notifications?

    πŸ“Œ Security Awareness – Notifies users when access is revoked or restored.
    πŸ“Œ Compliance – Ensures logs are maintained for security audits.
    πŸ“Œ Operational Efficiency – Eliminates manual notifications from IT.
    πŸ“Œ User Experience – Keeps employees informed about their account status.


    πŸ”Ή Prerequisites

    πŸ”Ή SMTP Server or Microsoft 365 Exchange Online (for sending emails)
    πŸ”Ή PowerShell module installed for Active Directory and Microsoft Graph

    πŸ”Ή Step 1: Configure Email Settings

    Define email settings for notifications:

    powershellCopyEdit$SMTPServer = "smtp.office365.com"
    $SMTPPort = 587
    $FromEmail = "[email protected]"
    $Credential = Get-Credential  # Enter email credentials for authentication
    

    πŸ”Ή Notifying Users When Their Account is Disabled

    Step 2: Identify Recently Disabled Users

    powershellCopyEdit$DisabledUsers = Get-ADUser -Filter {Enabled -eq $false} -Properties DisplayName, EmailAddress, Manager | 
        Select-Object DisplayName, EmailAddress, Manager
    

    βœ… Finds all recently disabled users


    Step 3: Send Email Notifications

    powershellCopyEditforeach ($User in $DisabledUsers) {
        $Subject = "Your Account Has Been Disabled"
        $Body = @"
    Hello $($User.DisplayName),
    
    Your account has been disabled due to security policies or organizational requirements. 
    If you need further assistance, please contact IT Support.
    
    Best regards,  
    IT Support Team
    "@
    
        Send-MailMessage -To $User.EmailAddress -From $FromEmail -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $Credential
    }
    

    πŸ“Œ Notifies users that their access has been disabled.


    Step 4: Notify Their Manager (Optional)

    If users have managers assigned in Active Directory, notify them too:

    powershellCopyEditforeach ($User in $DisabledUsers) {
        $Manager = Get-ADUser -Identity $User.Manager -Properties EmailAddress
        if ($Manager.EmailAddress) {
            $ManagerSubject = "Account Disabled Notification - $($User.DisplayName)"
            $ManagerBody = @"
    Hello,
    
    The account for $($User.DisplayName) has been disabled. 
    Please reach out to IT if further actions are required.
    
    Best regards,  
    IT Support Team
    "@
            Send-MailMessage -To $Manager.EmailAddress -From $FromEmail -Subject $ManagerSubject -Body $ManagerBody -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $Credential
        }
    }
    

    πŸ“Œ Managers are informed about user account deactivation.


    πŸ”Ή Notifying Users When Their Account is Re-Enabled

    Step 5: Identify Recently Re-Enabled Users

    powershellCopyEdit$ReEnabledUsers = Get-ADUser -Filter {Enabled -eq $true} -Properties DisplayName, EmailAddress | 
        Select-Object DisplayName, EmailAddress
    

    βœ… Finds all users who were just re-enabled


    Step 6: Send Account Re-Enablement Notifications

    powershellCopyEditforeach ($User in $ReEnabledUsers) {
        $Subject = "Your Account Has Been Re-Enabled"
        $Body = @"
    Hello $($User.DisplayName),
    
    Your account has been re-enabled, and you can now log in as usual.  
    If you experience any issues, please contact IT Support.
    
    Best regards,  
    IT Support Team
    "@
    
        Send-MailMessage -To $User.EmailAddress -From $FromEmail -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $Credential
    }
    

    πŸ“Œ Notifies users that their access has been restored.


    πŸ”Ή Automating Notifications for Azure AD Users

    If managing Azure AD, use Microsoft Graph PowerShell.

    Step 7: Install & Connect to Azure AD

    powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser -Force
    Connect-MgGraph -Scopes "User.ReadWrite.All", "Mail.Send"
    

    Step 8: Identify Disabled Users in Azure AD

    powershellCopyEdit$DisabledAzureUsers = Get-MgUser -Filter "accountEnabled eq false" -Property DisplayName, Mail | 
        Select-Object DisplayName, Mail
    

    Step 9: Send Notification to Disabled Azure AD Users

    powershellCopyEditforeach ($User in $DisabledAzureUsers) {
        $Subject = "Your Account Has Been Disabled"
        $Body = "Hello $($User.DisplayName),`n`nYour account has been disabled. Contact IT for assistance."
        
        Send-MgUserMail -UserId $User.Mail -Message @{
            Subject = $Subject
            Body = @{ Content = $Body; ContentType = "Text" }
        }
    }
    

    πŸ“Œ Azure AD users will receive an email alerting them about their account status.


    πŸ”Ή Automating the Process with Task Scheduler

    To automate the notifications:

    1️⃣ Save the script as AccountNotifications.ps1
    2️⃣ Open Task Scheduler β†’ Create Basic Task
    3️⃣ Set Trigger (e.g., Daily at 8 AM)
    4️⃣ Set Action β†’ Start a Program β†’ powershell.exe -File C:\Scripts\AccountNotifications.ps1
    5️⃣ Save & Run

    πŸ“Œ Now, account status changes will trigger email notifications automatically.


    πŸ”Ή Summary

    βœ… Users receive notifications when their account is disabled/re-enabled.
    βœ… Managers get alerts about changes to their team’s access.
    βœ… Automation ensures no manual emails are needed.
    βœ… Works for both Active Directory & Azure AD.
    βœ… Logs can be exported for security compliance.

    By implementing this automated notification system, IT teams can streamline account management, improve communication, and enhance security awareness. πŸš€

    Enforcing MFA Before Re-Enabling User Accounts – PowerShell Automation

    πŸ”Ή Introduction

    Multi-Factor Authentication (MFA) is a crucial security layer that helps prevent unauthorized access, especially after a user account is disabled and later re-enabled. Before restoring access, it’s best practice to enforce MFA enrollment to enhance security and prevent potential account compromise.

    This blog provides a PowerShell script to:
    βœ… Automatically check MFA status before re-enabling accounts
    βœ… Require MFA enrollment before re-enabling
    βœ… Send notifications to users and IT teams


    πŸ”Ή Why Enforce MFA Before Re-Enabling Accounts?

    πŸ“Œ Security Enhancement – Prevents unauthorized access after re-enablement.
    πŸ“Œ Compliance Requirements – Many security frameworks require MFA enforcement.
    πŸ“Œ Risk Mitigation – Reduces the risk of compromised credentials being reused.
    πŸ“Œ Automation Efficiency – Ensures a seamless security-first workflow.


    πŸ”Ή Prerequisites

    πŸ”Ή Azure AD Module installed (Install-Module AzureAD)
    πŸ”Ή PowerShell with Admin Rights
    πŸ”Ή Global Administrator or Privileged Authentication Admin Role


    πŸ”Ή Step 1: Connect to Microsoft Entra ID (Azure AD)

    powershellCopyEditInstall-Module -Name AzureAD -Force
    Import-Module AzureAD
    Connect-AzureAD
    

    πŸ“Œ This will prompt for admin credentials to authenticate.


    πŸ”Ή Step 2: Identify Recently Disabled Users

    powershellCopyEdit$DisabledUsers = Get-AzureADUser -All $true | Where-Object { $_.AccountEnabled -eq $false } |
        Select-Object DisplayName, UserPrincipalName, ObjectId
    

    πŸ“Œ Finds all disabled user accounts.


    πŸ”Ή Step 3: Check MFA Enrollment Status

    powershellCopyEditforeach ($User in $DisabledUsers) {
        $MFAStatus = Get-MsolUser -UserPrincipalName $User.UserPrincipalName | Select-Object -ExpandProperty StrongAuthenticationMethods
        if ($MFAStatus -eq $null) {
            Write-Host "MFA not enabled for $($User.DisplayName). Enforcing MFA before re-enabling..." -ForegroundColor Yellow
            # Proceed to enforce MFA
        } else {
            Write-Host "MFA already enabled for $($User.DisplayName). Ready to re-enable." -ForegroundColor Green
        }
    }
    

    πŸ“Œ This script checks if MFA is enabled before proceeding.


    πŸ”Ή Step 4: Enforce MFA Enrollment for Users Without MFA

    powershellCopyEditforeach ($User in $DisabledUsers) {
        $MFAStatus = Get-MsolUser -UserPrincipalName $User.UserPrincipalName | Select-Object -ExpandProperty StrongAuthenticationMethods
        if ($MFAStatus -eq $null) {
            Write-Host "Forcing MFA registration for $($User.DisplayName)..."
            Set-MsolUser -UserPrincipalName $User.UserPrincipalName -StrongAuthenticationRequirements @(@{State="Enabled"; })
            
            # Send notification email to user
            $Subject = "MFA Enrollment Required Before Account Re-Enablement"
            $Body = "Hello $($User.DisplayName),`n`nYour account is being re-enabled, but MFA is required before accessing your account. Please complete MFA enrollment immediately."
            Send-MailMessage -To $User.UserPrincipalName -From "[email protected]" -Subject $Subject -Body $Body -SmtpServer "smtp.office365.com" -Credential (Get-Credential)
            
            Write-Host "MFA enforced and email notification sent to $($User.DisplayName)." -ForegroundColor Cyan
        }
    }
    

    πŸ“Œ This forces MFA enrollment and notifies the user via email.


    πŸ”Ή Step 5: Re-Enable the User Account

    powershellCopyEditforeach ($User in $DisabledUsers) {
        $MFAStatus = Get-MsolUser -UserPrincipalName $User.UserPrincipalName | Select-Object -ExpandProperty StrongAuthenticationMethods
        if ($MFAStatus -ne $null) {
            Write-Host "Re-enabling account for $($User.DisplayName)..." -ForegroundColor Green
            Set-AzureADUser -ObjectId $User.ObjectId -AccountEnabled $true
    
            # Notify the user
            $Subject = "Your Account Has Been Re-Enabled"
            $Body = "Hello $($User.DisplayName),`n`nYour account has been successfully re-enabled. You may now log in using MFA."
            Send-MailMessage -To $User.UserPrincipalName -From "[email protected]" -Subject $Subject -Body $Body -SmtpServer "smtp.office365.com" -Credential (Get-Credential)
    
            Write-Host "Account re-enabled and email sent to $($User.DisplayName)." -ForegroundColor Cyan
        }
    }
    

    πŸ“Œ Only users who have completed MFA enrollment will be re-enabled.


    πŸ”Ή Automating the Process

    To automate MFA enforcement before re-enabling accounts:

    1️⃣ Save the script as Enforce-MFA-AccountReenable.ps1
    2️⃣ Open Task Scheduler β†’ Create Basic Task
    3️⃣ Set Trigger (e.g., Daily at 8 AM)
    4️⃣ Set Action β†’ Start a Program β†’ powershell.exe -File C:\Scripts\Enforce-MFA-AccountReenable.ps1
    5️⃣ Save & Run

    πŸ“Œ Now, all disabled accounts must complete MFA before being re-enabled!


    πŸ”Ή Summary

    βœ… Users cannot log in until MFA is configured
    βœ… Automated enforcement ensures security compliance
    βœ… Users and IT teams are notified via email
    βœ… Script works for both Active Directory & Azure AD
    βœ… Scheduled automation eliminates manual work

    With this automation, IT teams can enforce MFA before restoring user access, ensuring security-first policies and preventing unauthorized logins. πŸš€

  • Viewing Conditional Access Sign-Ins via Azure AD Portal

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

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

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

    Automating Conditional Access Sign-In Monitoring with PowerShell

    Step 1: Install Required PowerShell Modules

    First, ensure you have the necessary modules installed.

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

    Step 2: Connect to Microsoft Graph API

    Authenticate to retrieve sign-in logs:

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

    Step 3: Retrieve Conditional Access Sign-Ins

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

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

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


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

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

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

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

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


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

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

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

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


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

    To receive email notifications for suspicious login attempts:

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

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


    πŸ”Ή Summary

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

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

  • Enhancing Security with Conditional Access in Azure AD

    Introduction

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

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


    πŸ”Ή What is Conditional Access?

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

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


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

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

    Step 1: Creating the Conditional Access Policy Manually

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

    πŸ”Ή Automating Conditional Access with PowerShell

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

    Step 2: Install Required PowerShell Modules

    powershellCopyEditInstall-Module -Name Microsoft.Graph -Scope CurrentUser
    

    Step 3: Authenticate and Connect to Microsoft Graph

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

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

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

    πŸ”Ή Best Practices for Conditional Access Policies

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


    πŸ”Ή Summary

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

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

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

    Introduction

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

    Prerequisites

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

    PowerShell Script

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

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

  • Provision Microsoft Intune

    Install-Module -Name Microsoft.Graph.Intune
    

    βœ… Intune is provisioned.

  • Tracert: What It Is & How to Use It

    tracert google.com
    

    βœ… Tracks network routes.

  • FSMO Roles & How to Identify Servers Holding the Role

    netdom query fsmo
    

    βœ… Identifies FSMO roles.

  • Restore Domain Naming Master in VMware

    Start-VM -VMName "DomainController"
    

    βœ… Restores a crashed Domain Naming Master.

  • Provisioning an Azure VM Using PowerShell

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

    βœ… Azure VM created successfully.

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

    Introduction

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

    Prerequisites

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

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

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

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

    2️⃣ PowerShell Method: Automate Azure AD Join

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

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

    powershellCopyEditGet-MDMEnrollmentStatus
    

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

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

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

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

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

    πŸ”Ή Step 3: Verify the Join Status

    powershellCopyEditdsregcmd /status
    

    πŸ“Œ The output should show AzureAdJoined : YES


    3️⃣ Auto-Enroll Devices via Microsoft Intune

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

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

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


    4️⃣ Troubleshooting & Best Practices

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

    Summary

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

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

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

    Overview

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


    Prerequisites

    Before proceeding, ensure:

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

    Step 1: Install and Connect to Microsoft Graph PowerShell

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

    Install Microsoft Graph PowerShell Module

    powershellCopyEditInstall-Module Microsoft.Graph -Scope CurrentUser
    

    Connect to Microsoft Graph with Required Scopes

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

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


    Step 2: Verify and Modify Cross-Tenant Access Policy

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

    View Current Cross-Tenant Access Settings

    powershellCopyEditGet-MgPolicyCrossTenantAccessPolicy | Format-List
    

    Enable Cross-Tenant Sync (If Disabled)

    powershellCopyEditUpdate-MgPolicyCrossTenantAccessPolicy -DefaultInboundAccessEnabled $true -DefaultOutboundAccessEnabled $true
    

    This command ensures that inbound and outbound sync is enabled.


    Step 3: Remove Conflicting Identity Types

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

    Check User Identities

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    Remove Phone-Based Authentication Method

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

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

    Confirm the Change

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    Ensure that “phone” is no longer listed.


    Step 4: Configure Cross-Tenant Sync Using PowerShell

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

    Enable Cross-Tenant Sync for a Specific Tenant

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

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

    Enable Automatic User Synchronization

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

    Check Sync Status

    powershellCopyEditGet-MgPolicyCrossTenantAccessPolicyConfigurationPartner -TenantId "<PartnerTenantID>"
    

    Step 5: Test and Verify Cross-Tenant Sync

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

    Force Sync for Testing

    powershellCopyEditStart-ADSyncSyncCycle -PolicyType Delta
    

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

    Check Sync Logs

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

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

    Final Thoughts

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

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

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

    Overview

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


    Prerequisites

    Before proceeding, ensure:

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

    Step 1: Install and Connect to Microsoft Graph PowerShell

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

    Install Microsoft Graph PowerShell Module

    powershellCopyEditInstall-Module Microsoft.Graph -Scope CurrentUser
    

    Connect to Microsoft Graph with Required Scopes

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

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


    Step 2: Verify and Modify Cross-Tenant Access Policy

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

    View Current Cross-Tenant Access Settings

    powershellCopyEditGet-MgPolicyCrossTenantAccessPolicy | Format-List
    

    Enable Cross-Tenant Sync (If Disabled)

    powershellCopyEditUpdate-MgPolicyCrossTenantAccessPolicy -DefaultInboundAccessEnabled $true -DefaultOutboundAccessEnabled $true
    

    This command ensures that inbound and outbound sync is enabled.


    Step 3: Remove Conflicting Identity Types

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

    Check User Identities

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    Remove Phone-Based Authentication Method

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

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

    Confirm the Change

    powershellCopyEditGet-MgUserAuthenticationMethod -UserId [email protected]
    

    Ensure that “phone” is no longer listed.


    Step 4: Configure Cross-Tenant Sync Using PowerShell

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

    Enable Cross-Tenant Sync for a Specific Tenant

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

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

    Enable Automatic User Synchronization

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

    Check Sync Status

    powershellCopyEditGet-MgPolicyCrossTenantAccessPolicyConfigurationPartner -TenantId "<PartnerTenantID>"
    

    Step 5: Test and Verify Cross-Tenant Sync

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

    Force Sync for Testing

    powershellCopyEditStart-ADSyncSyncCycle -PolicyType Delta
    

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

    Check Sync Logs

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

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

    Final Thoughts

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

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

  • Blog

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

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

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

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

    Root Cause

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

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

    Solution: Change Identity to Microsoft Authenticator

    To resolve this issue, follow these steps:

    1. Remove Phone-Based Identity

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

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

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

    3. Reattempt Cross-Tenant Sync

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