Published on

Disable Requrired Lab User

Authors
  • Name
    Jackson Chen
#Requires -RunAsAdministrator

cls

# Import Active Directory module
Import-Module ActiveDirectory

# Variables
$ReportPath = "D:\Logs\LAB User Decom Reports"
$strComputer = $env:COMPUTERNAME
$ExchangeServer = "ExchangeSrv01.lab.net"
$MailboxUpdateResult = $false
$DisableAccountOU = "OU=Disabled Accounts,DC=LAB,DC=NET"

# ------------------------------------------------------
# Function Name: Show-Menu
# Usage:
#      Display PowerShell window for user input
#      Display options to user to select
#
# Input: None
# Output: None
# ------------------------------------------------------
Function Show-Menu
{
    Param (
    [String] $Title = " Warning - This will decommissioned the requried LAB user account."
    )
    Clear-Host
    Write-Host "`n ********** $Title ********** " -ForegroundColor Red
    Write-Host "`n"
    Write-Host " The following tasks will be performed:`n"
    Write-Host "`t1. Disable user account.`n"
    Write-Host "`t2. Record the decommission description.`n"
    Write-Host "`t3. Remove user groupr membership.`n"
    Write-Host "`t4. Move the user account to Disabled Accounts OU.`n"
    Write-Host "`t5. Hide user from GAL.`n"
    Write-Host "1: Type 'yes' or 'YES' to confirm that you are very sure to decommission the required LAB user account. " -ForegroundColor Red -BackgroundColor White
    Write-Host "2: or press any other key to exit" -ForegroundColor Green
}

# ------------------------------------------------------
# Function Name: Identification
# Usage:
#      Identify who and when the services are updated
#
# Input: N/A
# ------------------------------------------------------
Function Identification
{
    # Identify the running user and the run time
    $RunUser = [Security.Principal.WindowsIdentity]::GetCurrent().Name
    $RunTime = Get-Date

    # Record the user and run time
    Return "The require LAB USER task was carried by $RunUser from $strComputer at $RunTime `n"
}


# ------------------------------------------------------
# Function Name: UpdateUserMailbox
# Usage:
#      Identify who and when the services are updated
#
# Input:         UserName
# ------------------------------------------------------
Function UpdateUserMailbox ([String] $UserName)
{
    # Variable
    $Computer = "ExchangeSrv01.lab.net"

    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$Computer/PowerShell/" -Authentication Kerberos
    Import-PSSession $Session -AllowClobber

    Try {
        # Hide user from GAL
        Set-Mailbox -Identity $UserName -HiddenFromAddressListsEnabled $true

        # Set mailbox size quota to zero
        Set-Mailbox -Identity $UserName -IssueWarningQuota 0 -ProhibitSendQuota 0 -ProhibitSendReceiveQuota 0 -UseDatabaseQuotaDefaults $false
    }
    Catch {
        # Do Nothing
    }    
    
    Remove-PSSession $Session
}


# ------------------------------------------------------
# Main
# ------------------------------------------------------
# Ask user for confirmation 
Show-Menu
$Input = Read-Host "Please make a selection."

If ($Input -eq 'yes') {
    $USER = Read-Host -Prompt 'Input the User Name'
    $Jobnum = Read-Host -Prompt 'Input the Job Number'
    $timestamp = Get-Date -UFormat "%d/%m/%Y %R"

    Try {
        # Verify the user in Active Directory, continue if the use exist
        If (Get-ADUser -Identity $USER) {
            Write-Host " Processing user $USER"
            "Username: $USER" | Add-Content "$ReportPath\$USER-Decommission-Report.txt"
            "Job Number: $Jobnum" | Add-Content "$ReportPath\$USER-Decommission-Report.txt"
            "Time : $timestamp" | Add-Content "$ReportPath\$USER-Decommission-Report.txt"
    
            # Record user group membership
            "The following groups will be removed from $USER" | Add-Content "$ReportPath\$USER-Decommission-Report.txt"
            
            # Obtain user distinguishedName and group membership
            Get-ADUser -Identity $USER | Select-Object distinguishedName | Out-File -Encoding ascii -Append "$ReportPath\$USER-Decommission-Report.txt"
            Get-ADPrincipalGroupMembership -Identity $USER | Select-Object Name,SamAccountName | Out-File -Encoding ascii -Append "$ReportPath\$USER-Decommission-Report.txt"
    
            # Record the admin user who carry out the LAB user decommission
            Identification | Add-Content "$ReportPath\$USER-Decommission-Report.txt"
            Write-Output ".....Report Complete....."
    
            # Sleep
            Start-Sleep -s 2
    
            # Disable user account
            Disable-ADAccount -Identity $USER

            # Remove user group membership
            Get-ADPrincipalGroupMembership -Identity $USER | `
                Where-Object {$_.Name -notlike "Domain Users"} | `
                ForEach-Object {
                    # Automatically remove user group membership
                    Remove-ADPrincipalGroupMembership -Identity $USER -MemberOf $_ -Confirm:$false
                } #Confirmation to remove Group Memberships from user

             # Move user to Disabled Accounts OU
             Get-ADUser $USER | Move-ADObject -TargetPath $DisableAccountOU
             
             #Update USER Description with Time/Date and Job Number
             Set-ADUser -Identity $USER -Description "Decommissioned on $timestamp Job Number $Jobnum"
             Write-Output "$USER has been decommissioned on $timestamp Job Number $Jobnum"
        }

        # Hide user from GAL and set user mailbox quota to zero
        UpdateUserMailbox $USER

    }
    Catch {
        # Inform support team to verify the LAB user account and try again
        Write-Host "`nNot able to disable $USER, please check the user account and try again." -ForegroundColor Red
    }
}

Another script

#Requires -RunAsAdministrator

cls

# Import Active Directory module
Import-Module ActiveDirectory

# Variables
$timestamp = Get-Date -UFormat "%d/%m/%Y %R"
$datestamp = Get-Date -UFormat "%d/%m/%Y"
$JobNum = "" # Verify HelpDesk for Job Number

# Disabled User OU
$Company1_InactiveOU = "OU=Company1_Inactive,DC=LAB,DC=NET" # Company1 Disabled Users Only
$Company2_InactiveOU = "OU=Company2_Inactive,DC=LAB,DC=NET" # Company2 Disabled Users Only
$InActiveOU = "OU=Inactive,DC=LAB,DC=NET" # Disabled User OU for all other companies

$ReportPath = "D:\Logs\LAB User Decom Reports"
$Computer = $env:COMPUTERNAME

$UserList = "\\$Computer\D$\Inputs\LAB_Decom_User_List\LAB_Decom_UserList.txt"
$Report = "\\$Computer\D$\Logs\LAB User Decom Reports\LAB-Users-Decommission-Report.txt"


# ------------------------------------------------------
# Main
# ------------------------------------------------------

# Obtain the user list that need to be disabled
$AllUsers = Import-Csv $UserList
$Users = $AllUsers.name

# Proceed if the user list is not empty
If ($Users) {
    # Update report
    "Disable Require LAB Users on: $timestamp" | Add-Content $Report
    
    # Process every required disable user
    ForEach ($User in $Users) {
        Try {
            If (Get-ADUser -Identity $User) {
                Write-Host "Disabling user: $User" -ForegroundColor Green
                $UserInfo = Get-ADUser -Identity $User | Select-Object DistinguishedName,Name,SamAccountName
                $UserDN = $UserInfo.DistinguishedName
                $UserName = $UserInfo.Name
                $UserSAM = $UserInfo.SAMAccountName
                $UserDescription = "Disabled on $datestamp" + " $JobNum "

                # Disable user account
                Disable-ADAccount -Identity $User
                "$UserName - has been disabled." | Add-Content $Report

                # Update Users Description with Date and Job Number
                Set-ADUser -Identity $User -Description $UserDescription
                "$UserName - Description has been updated." | Add-Content $Report
                
                # Set extensionAttribute2 to TestOnly
                Set-ADUser -Identity $UserSAM -Clear "extensionAttribute2"
                Set-ADUser -Identity $UserSAM -Add @{extensionAttribute2 = "TestOnly"}
                "$UserName - extensionAttribute2 has been updated." | Add-Content $Report

                # User belongs to two groups by default: "Domain Users" & "NAT_AUS"
                $NumGroups = (Get-ADPrincipalGroupMembership -Identity $UserSAM | Measure-Object count).count
                If ($NumGroups -gt "2") {
                    "$UserName ($UserSAM) - Group Membership - $timestamp" | Out-File -Encoding Ascii -Append "\\$Computer\D$\Logs\LAB User Group Membership Reports\$UserName-GroupMemberhip.txt"
                    Get-ADPrincipalGroupMembership -Identity $UserSAM `
                        | ?{(($_.Name -notlike "Domain Users") -and ($_.Name -notlike "ExcludeUsers"))} `
                        | Select-Object Name,SamAccountName `
                        | Out-File -Encoding Ascii -Append "\\$Computer\D$\Logs\LAB User Group Membership Reports\$UserName-GroupMemberhip.txt"
                
 
                    # Remove user group membership
                    Get-ADPrincipalGroupMembership -Identity $UserSAM `
                        | ?{($_.Name -notlike "Domain Users") -and ($_.Name -notlike "ExcludeUsers")} `
                        | ForEach-Object {
                            # "$_.Name" | Out-File -Encoding ascii -Append "\\$Computer\D$\Logs\LAB User Group Membership Reports\$UserName ($UserSAM)-GroupMemberhip.txt"
                            Remove-ADPrincipalGroupMembership -Identity $UserSAM -MemberOf $_ -Confirm:$false                    
                          }
                
                    # Update disabled user group membership cleanup report
                    "$UserName`t($UserSAM) - Group Memberships have been cleaned up." | Add-Content $Report
                }
                
                # Move disable user to the required disabled user OU
                # Process Company1 Users
                If ($UserDN -like "*Company1_Users*") {
                    Write-Host "Process Company1 User: $UserName" -ForegroundColor Yellow
                    Get-ADUser $User | Move-ADObject -TargetPath $Company1_InactiveOU
                    "$UserName - has been moved to Company1_Inactive OU." | Add-Content $Report
                }
                # Process Company2 Users
                ElseIf ($UserDN -like "*Company2_Users*") {
                    Write-Host "Process Company2 User: $UserName" -ForegroundColor Yellow
                    Get-ADUser $User | Move-ADObject -TargetPath $Company2_InactiveOU
                    "$UserName - has been moved to Company2_Inactive OU." | Add-Content $Report
                }
                # Process other Companies Users
                Else {
                    Write-Host "Process other Companies user: $UserName" -ForegroundColor Yellow
                    Get-ADUser $User | Move-ADObject -TargetPath $InActiveOU
                    "$UserName - has been moved to Inactive OU." | Add-Content $Report
                }
            }
        }
        Catch {
            Write-Host "The user ($user) does not exist in LAB, please verify the user." -ForegroundColor Red
        }
    }
    "`n" | Add-Content $Report
    Write-Host "All required users have been disabled." -ForegroundColor Green
}