Today, About a list of 1000 user’s was plopped on my calendar to audit and remove from our environment if not used. I throw together this script after adding all the users into a single text file and running through them and generated an output that would then fit into our Deprovisioning framework from Caradigm Sentillion, being aware of not disable / deleting active employees. Worked like a charm, I added a time span of not logging in the last 90 days to be safe.

Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host

$myArray = New-Object System.Collections.ArrayList

foreach($line in get-content "C:\TermList.txt")
{
    try
    {
        $recipients = $line -split [RegEx]::Escape(",")
        $samAccountName = $recipients[0].trim()

        #Get-ADUser -Identity $samAccountName -Properties enabled, LastLogonDate, LastLogonTimeStamp
        #Get-ADUser -LDAPFilter "(sAMAccountName=$samAccountName)"  | Select-Object -Property samaccountname, enabled, LastLogonDate, LastLogonTimeStamp, msDS-LastSuccessfulInteractiveLogonTime

        $User = Get-ADUser -Identity $samAccountName -Properties enabled, LastLogon, LastLogonDate, LastLogonTimeStamp
        If ($User -ne $Null) 
        {
            if ($User.enabled -eq $false)
            {
                if ($User.LastLogonDate -eq $Null)           
                { 
                    Write-Host $User.samAccountName $User.enabled "BLANK"
                    [void] $myArray.Add($User.samAccountName)
                }
                else
                {
                    if ($User.LastLogonDate -gt [datetime]::Today.AddDays(-90))
                    {
                        #Write-Host $User.samAccountName $User.enabled $User.LastLogon $User.LastLogonTimeStamp $User.LastLogonDate #User has logged in the last 90days
                    }
                    else
                    {
                        Write-Host $User.samAccountName $User.enabled $User.LastLogon $User.LastLogonTimeStamp $User.LastLogonDate
                        [void] $myArray.Add($User.samAccountName)
                    }
                }
            }
        }
    }
    catch
    {
    }
}

foreach ($Employee in $myArray)
{
    Write-Host "!DELETE_USER|$Employee"
}

Leave a Reply

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

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax