Disabling AD users via CSV import sort of...

Hi Everyone,

I’m not even sure if this is possible to do but i’ve been asked to look into creating a script that will look at list of users from an imported CSV and from that it will compare it to a list of users within a speficic AD OU, if a user is found to be missing from the CSV but is still in the AD OU it will disable the account and move it to another OU and then spit out a report to say which users (if any) have been disabled.

Is this possible to do and if so how?

I am relatively new to Powershell and only know the basics, I’m not asking for someone to literally write this for me I just want a general idea of what kind of commands I could use to achieve this (if possible).


Get-ADUser (RSAT Tools Installed) or Get-QADUser (Quest AD Cmdlets) which either can set the scope to the OU one level or search recursively

Your CSV will be object 1 and the users from AD will be object 2. You will need to have the same property name (e.g. samAccountName) for Compare-Object and then can choose a $_.SideIndicator and then use Set-ADUser (or Set-QADUser) and Move-ADObject ( or Move-QADObject) to accomplish the other items.

Get started with some code and members will give you tips and help make the script work as expected, provide error handling and make it efficient.

In general, you’ll get better performance from AD queries if you use the -Filter or -LdapFilter parameters as much as possible. This lets the AD domain controller worry about returning the accounts you’re interested in, and keeps network traffic to a minimum. In this case, I’d start with something along these lines:

$sourceOU = 'OU=SomeOU,DC=some,DC=domain,DC=com'

$filter = Import-Csv -Path 'yourCsvFile.csv' |
          ForEach-Object { "SamAccountName -ne '$($_.SamAccountName)'" }

$filter = $filter -join ' -and '

$usersToMove = Get-ADUser -SearchBase $sourceOU -Filter $filter

foreach ($user in $usersToMove)
    # Disable and move the user account.
    # Output whatever information you like.

Here we’re just using the CSV file to build a filter string dynamically. If the CSV contains User1, User2, and User3 as SamAccountNames, the $filter variable will wind up containing “SamAccountName -ne ‘User1’ -and SamAccountName -ne ‘User2’ -and SamAccountName -ne ‘User3’” when Get-ADUser is called.

The code inside the foreach loop is more straightforward, with calls to Set-ADUser and Move-ADObject (likely with error handling), plus whatever output you need to produce.