How to check if an AD username is already used
Thank you in advance for your help. I found something related at the following link but was unable to find the solution I was looking for through here. Check existance of domain accounts with Powershell script
What I am trying to do is take usernames from a list that is already generated into a CSV file from another script I am running.
Once I have these usernames (sAMAccountname) I want to check if that username is already being used. If it is I want it to be shown, perhaps via Echo, and then to continue checking the other names. If it's not then it should simply continue checking other names.
Here is what I have up to now. ( Keep in mind I am a complete Powershell novice and I am only doing this out of absolute need )
Import-Module ActiveDirectory -ErrorAction Continue
$UserCSV = import-csv "\\fs1\DisasterRecovery\Source Controlled Items\WindowsPowerShell\Test scripts\Import Production Users\Users.csv"
$UserList = $UserCSV.sAMAccountname
foreach($User in $UserList)
{
if (Get-ADUser -Filter {sAMAccountname -eq $User} ) {
# Exists
#echo Already Exists
} else {
SilentlyContinue
}
}
Solution 1:
If you're using Powershell 3 or better, there is no need for Import-Module ActiveDirectory
. PS will automatically load the module for you as soon as you use a cmdlet from that module. Use $PSVersionTable
to know for sure, but I think you are using PS 3 or better because you appear to use an automatic foreach in your code, and automatic foreach didn't become available until PS 3.
Furthermore, there's no point in continuing if the module fails to load, since it is critical to the rest of the script, so the -ErrorAction Continue
doesn't make sense either. I'd strike the entire first line.
Line two where you Import-CSV is OK. The $UserList
variable seems superfluous. From there I'd probably do something like this:
$UserCSV = Import-Csv C:\Users\Administrator\test.csv
Foreach ($User in $UserCSV)
{
Try
{
# Use "EA Stop" to ensure the exception is caught.
$U = Get-ADUser $User.sAMAccountName -ErrorAction Stop
Write-Host "$($User.SamAccountName) is already in use."
}
Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
{
# The user was not found!
Write-Warning "$($User.SamAccountName) was not found in this domain!"
}
Catch
{
# Some other terrible error occured!
Write-Error "OHSHI"
}
}
Solution 2:
I haven't tested this, but the structure would be more like:
Import-Module ActiveDirectory -ErrorAction Continue
$UserCSV = import-csv "\\fs1\DisasterRecovery\Source Controlled Items\WindowsPowerShell\Test scripts\Import Production Users\Users.csv"
foreach($row in $UserCSV)
{
$userAccount = Get-ADUser -Filter {sAMAccountname -eq $row.sAMAccountname}
if ($userAccount) {
Write-Host "User $($row.sAMAccountname) exists"
}
}