Checking if an AD object still exist

PowerShell LogoLast week I was talking to an friend, he is an system administrator with a large insurance company in the Netherlands. He told me that at his site there is a huge problem with cleaning up home- and profile folders. This problem was never really acknowledged because there was always enough storage. Recently they have been receiving messages from the storage management system that they are reaching the limits of there storage capacity.

They went browsing thru there data three to see if they could locate unnecessary data on sight. While they where doing that they stumbled upon there home folder en profile location. They found way more home folders and profile folders than there are user objects in there Active Directory. He was looking for a way to filter out which home folders could be deleted because the corresponding users account no longer existed in the active directory.

With this issue in mind I wrote an small PowerShell script that loads a list of usernames and then checks if there is an AD object for that username.

Import-Module ActiveDirectory

$UserList = get-content .\users.txt
Foreach ($Item in $UserList) {
$user = $(try {Get-ADUser $Item -server dc001.insurance.local} catch {$null} )

if ($user -ne $null) {
"$item;YES" >> .\Output.csv
} else {"$item;NO" >> .\Output.csv
    }
}

What the script does is it try’s to locate an AD object that matches the username from the list. If it fails to locate the object the script returns an null value.  The script that creates an .csv file to store the output. You can use the output.csv to perform furtherfuther actions.