Friday, January 26, 2024

Disable guest account from Azure AD reading CSV file

#This PowerShell script is used to read a CSV file having list of User Principal name (not email)
#and disable the account in azure AD

# Install the AzureAD PowerShell module if not already installed
Install-Module -Name AzureAD -Force -AllowClobber -Scope CurrentUser

# Import the AzureAD module
Import-Module AzureAD



# Connect to Azure AD
Connect-AzureAD # -Credential $credential

# Specify the path to your CSV file
$csvFilePath = "C:\Report\Final\UserPrinicpalList.csv"


    # Read the CSV file
    $csvData = Import-Csv -Path $csvFilePath

    # Iterate through each row in the CSV
    foreach ($row in $csvData) {
        $upn = $row.UserPrincipalName

        # Get the user object from Azure AD
        
        $azureADUser = Get-AzureADUser -Filter "UserPrincipalName eq '$upn'"

        if ($azureADUser) {
            Write-Host  $email -ForegroundColor Green
            # Disable the user account
            Set-AzureADUser -ObjectId $azureADUser.ObjectId -UserPrincipalName $upn -AccountEnabled $false

            Write-Host "Azure AD account for $email has been disabled."
        } else {
            Write-Host  $upn -ForegroundColor Red
            Write-Host "User with email $upn not found in Azure AD."
        }
    }

No comments:

Post a Comment

HTML

Script:

JS