Thursday, 14 May 2026

Disable the Accounts, Move the account to UnSync OU.

             $users = Get-Content C:\Temp\kumar\admaccount1.txt


            $targetou = "OU=Unmanaged Users,DC=Test,DC=com"


                        foreach ($usr in $users){


                        $userdn = Get-Aduser $usr -Properties * | Select-Object -ExpandProperty DistinguishedName


                            if ($usr){


                                Disable-ADAccount $usr


                            if ($usr) {


                            Move-ADObject -Identity $userdn -TargetPath $targetou


                                }


                                }


                                }

Adding Guest Accounts into Azure AD Groups

 We manage several enterprise Azure AD applications that grant access to both internal users and external guest accounts. Frequently, we receive bulk requests to add guest accounts into Azure AD groups. To streamline this process and reduce manual effort, we developed a script that automates the addition of guest accounts to the required groups.




#[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;

# Connect to Azure AD

#Connect-AzureAD


# Import users from CSV

$Users = get-content "C:\temp\kumar\users.txt"


# Specify the group

$Group = Get-AzureADGroup -ObjectId abcdef-xyx-123


# Add each user to the group

foreach ($User in $Users) {

    $userObjectId = (Get-AzureADUser -Filter "Mail eq '$User'").ObjectID

    if ($userObjectId -ne $null) {

        Add-AzureADGroupMember -ObjectId $Group.ObjectId -RefObjectId $userObjectId -ErrorAction SilentlyContinue

        Write-Host "WIP $User"

    }

}


#$userObjectId = (Get-AzureADUser -Filter "Mail eq 'abc@xyz.com'").ObjectID

Custom Password Generator

 The below script would help you to generate passwords randomly, instead of using public sites, you can generate the password by yourself. 


$Password = New-Object -TypeName PSObject

$Password | Add-Member -MemberType ScriptProperty -Name "Password" -Value { ("123456789!@#$%&0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".tochararray() | sort {Get-Random})[0..15] -join '' }

$Password #| Out-GridView

Suspicious Active Directory Account Disable

 Recently, our security team detected suspicious activity involving approximately 200 accounts. They immediately engaged me to disable these accounts and requested that comments be added during the disable process to ensure the service desk team does not inadvertently re-enable them. To meet this requirement, we developed a lightweight script that automated the account disable action while inserting the necessary comments for tracking and control.


$listofuser = Get-content C:\Temp\user.txt


#$Comment = "Account disabled on 05-Dec-2025 by Admin IncNumber"


foreach ($usr in $listofuser) {


    # Disable the account

    Get-Aduser -Filter {UserPrincipalName -eq $usr} | Disable-ADAccount


    # Update the description field

  Get-Aduser -Filter {UserPrincipalName -eq $usr} | Set-ADUser -Description $Comment

   # Get-Aduser -Filter {UserPrincipalName -eq $usr} -Properties Description |Select-Object Name,UserPrincipalName,Enabled,Description | Export-Csv C:\Temp\report.csv -NoTypeInformation -Encoding UTF8 -Append

  #  Write-Host "Account Disabled for the user $usr | $comment" -ForegroundColor Green



}


Privilege Account MFA Method Report:-

 Our security team requested an assessment to identify privileged accounts and verify their MFA status. To address this requirement, we began developing a script that retrieves all _ADM accounts along with the details of their configured MFA methods.



# [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;


#Connect-MgGraph -Scopes "Directory.Read.All","UserAuthenticationMethod.Read.All"


$searchBase = "OU=Privileged,OU=Managed Users,DC=TEST,DC=com"


$listofusers = Get-ADUser -SearchBase $searchBase -Filter {samaccountname -like "*_adm"} -Properties * | Select-Object -ExpandProperty UserPrincipalName


foreach ($usr in $listofusers){



# Get all users and check their authentication methods

$results = Get-MgUser -UserId $usr | ForEach-Object {

    $methods = Get-MgUserAuthenticationMethod -UserId $_.Id

    [PSCustomObject]@{

        DisplayName = $_.DisplayName

        UserPrincipalName = $_.UserPrincipalName

        MFAEnabled = ($methods | Where-Object {$_.AdditionalProperties['@odata.type'] -like "*microsoft.graph.microsoftAuthenticatorAuthenticationMethod*"}).Count -gt 0

    }# Export to CSV

$results | Export-Csv -Path "C:\Temp\kumar\MFAStatus.csv" -NoTypeInformation -Append

}

}


Active Directory Privilege Account expire match User Regular Account:-

 We recently encountered a surge of incidents where numerous administrator accounts were found to be expired, leading to a flood of support tickets. Upon investigation with several users, we discovered that the Identity Access Management (IAM) team had identified approximately 1,500 user accounts that had expired and subsequently renewed them due to organizational changes. However, this renewal process inadvertently caused the associated _ADM accounts to also expire.


Unfortunately, when the IAM team extended the user accounts, they only updated the regular accounts and overlooked the privileged (_ADM) accounts. As a result, the AD team was later requested to align the expiration dates of the 1,500 user accounts with their corresponding _ADM accounts. To resolve this, we developed a script that synchronized and updated the expiration dates of the privileged accounts to match those of the regular accounts.

$listofusers = Get-content C:\Temp\user.txt


foreach ($usr in $listofusers) {


$date = Get-aduser $usr -Properties AccountExpirationDate | Select-Object -ExpandProperty AccountExpirationDate

$ConvertADm2Normal= Get-ADUser $usr | Select-Object -ExpandProperty SamAccountName

$newName = $ConvertADm2Normal + "_Adm"


Get-ADUser -Identity $newName | Set-ADAccountExpiration -DateTime:$date -Server test.com


#Get-ADUser $newName -Properties AccountExpirationDate | Select-Object Name,AccountExpirationDate



}


Wednesday, 13 May 2026

Last Login Report both On Prem and Azure

We often receive request for collecting Last login report both on prem and Azure AD sign in login, we have build the script to collect this. 
Sharing interesting tiny script that make your life more easier :) 
# Verify your machine having proper firewall rules in place. 
# Test-NetConnection login.microsoftonline.com -Port 443
# Test-NetConnection autologon.microsoftazuread-sso.com -Port 443

# Enable Tls12 protocol
# [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Verify Microsoft Site
# Invoke-WebRequest -Uri "https://login.microsoftonline.com" -UseBasicParsing

# This report need some Microsoft Graph Command, hence we are installing the modules. 

# Install-Module Microsoft.Graph -Scope AllUsers -Force
# Install-Module Microsoft.Graph -Scope AllUsers -Force -AllowClobber

# Connect Microsoft Graph by using your Azure AD credentials. 

# Connect-MgGraph -Scopes "User.Read.All","Directory.Read.All"

# $Cred = Get-Credential

$listofusers = Get-content C:\temp\kumar\azuread1.txt

$Properties = @("Id","DisplayName","UserPrincipalName","SignInActivity")

foreach ($usr in $listofusers){
#$Users = Get-MgUser -All -Property $Properties | Select-Object -First 100

    $Users1 = get-aduser -filter {UserPrincipalName -eq $usr} -Properties * -Server Server1.test.com -Credential $Cred | Select-Object SamAccountName,LastLogonDate
    $Users = Get-MgUser -Filter "userPrincipalName eq '$usr'" -Property $Properties

    $Users | Select-Object DisplayName, UserPrincipalName, @{Name="LastLoginDate";Expression={$_.SignInActivity.LastSignInDateTime}}

         # Merge into one object
        $Combined = [PSCustomObject]@{
            AzureDisplayName       = $Users.DisplayName
            AzureUserPrincipalName = $Users.UserPrincipalName
            AzureLastLoginDate     = $Users.SignInActivity.LastSignInDateTime
            OnPremSamAccountName   = $Users1.SamAccountName
            OnPremLastLogonDate    = $Users1.LastLogonDate
        }

        # Output or export
        $Combined | Export-Csv "AzureAD_LastLogin.csv" -NoTypeInformation -Append


}