Disable users using last logon via Powershell

Today I wanna share with you my script to disable users using last logon attribute.

As an input for the script CSV file with account header is used, in which SamAccountNames are stored.
For your purposes it can be adjusted to gather all users from Active Directory, but in my case I only wanted to check few accounts 🙂

Script will also ask about number of years for which users was not logged on. Base on that it will calculate acceptable last logon date attribute.

# Import Active Direcotry module
$ADModule = Get-Module ActiveDirectory
if($ADModule -eq $null)
{
    [System.Windows.MessageBox]::Show('AD module not installed, script will be closed','','Ok','Error')
    exit
}
Import-Module ActiveDirectory

# Function to check path of the CSV file
Function Get-CSVName($initialDirectory)
{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
    
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.Title = "Choose CSV file with users..."
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.filter = "CSV (*.csv)| *.csv"
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.filename
    
}

# Input about number of  years for last logon
$TimeStamp = Read-host -Prompt "Provide number of years for which users was not logged on: " 
while($TimeStamp -notmatch “[0-9]”)
{
    Write-Host Years number was not provided in correct format! -ForegroundColor Red
    $TimeStamp = Read-host -Prompt "Provide number of years for which users was not logged on: " 
}
while($TimeStamp -eq 0)
{
    Write-Host Timestamp should be bigger than 0  -ForegroundColor Red
    $TimeStamp = Read-host -Prompt "Provide number of years for which users was not logged on: " 
}
$PastDate = (Get-Date).AddYears(-$TimeStamp)

# CSV file error handling
$CSVFile = Get-CSVName
if([string]::IsNullOrEmpty($CSVFile))
{
    $CSVDialog = [System.Windows.MessageBox]::Show('CSV file not selected. Would you like to try once again ?','CSV file not selected','YesNo','Warning')
    If($CSVDialog -eq "yes")
    {
        $CSVFIle = Get-CSVName
    }
    else
    {
        [System.Windows.MessageBox]::Show('Users input file not selected, script will be closed','','Ok','Error')
        exit
    }
}
$Accounts = (Import-Csv -Path $CSVFile).account

# Foreach accounts in CSV file
foreach($Account in $Accounts)
{
    $LastLogon, $User = $Null
    # Check if user exists in AD
    $User = Get-ADUser -Identity $Account -Properties LastLogonDate -ErrorAction SilentlyContinue
    $LastLogon = $User.LastLogonDate
    if($User)
    {
        # Check if last logon attribute is empty
        if(!([string]::IsNullOrEmpty($LastLogon)))
        {
            # If last logon attribute is not empty check if it's older than provided number of years
            if($LastLogon -lt $PastDate)
            {
                # Calculate number of days from last logon
                $time = (New-TimeSpan -Start $LastLogon -End (Get-Date)).Days
                Write-Host $Account last logged $time days ago, it will be deleted -ForegroundColor Yellow
                Try
                {
                    # Disable user if logondate id older than provided number of years
                    Set-ADUser -Identity $User -Enabled $false
                    Write-Host User $Account has been disabled -ForegroundColor Green
                }
                Catch
                {
                    # If some problem occured catch an error
                    $exc = $_.exception.Message
                    Write-Host User $Account was not disabled. Error : $exc -ForegroundColor Yellow
                }
                
            }
            else
            {
                $time = (New-TimeSpan -Start $LastLogon -End (Get-Date)).Days
                Write-Host $Account last logged $time days ago
            }
        }
        else
        {
            Write-Host $Account logondate is empty, user will not be disabled -ForegroundColor Red
        }
    }
    else
    {
        Write-Host $Account can not be found in Active Directory -ForegroundColor Red
    }
}
Pause

I hope it will be usefull for some of you.
Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.