Hello everyone
I am trying to create a script that checks whether a user exists or not in AD. I have seen other posts with similar problems but I can not make mine work. :(
Here is my script which to be honest is made up of bits and pieces from the web:
-----------------------------------------------------------------------------------
Import-module activedirectory
$objOU=[ADSI]"LDAP://OU=dummyOU,DC=testad,DC=bk,DC=co,DC=uk"
$source=import-csv ".\Book1.csv"
foreach ($data in $source)
{
#store values from $source to variables
$cn=$data.cn
$firstName=$data.firstName
$lastName=$data.lastName
$userPrincipalName=$data.UserPrincipalName + "@testad.bk.co.uk"
$sAMAccountName=$data.samAccountName
$password=$data.password
$fullname=$firstname + " " +$lastname
#Write-Host $fullname
$pattern="$fullname"
#write-host $pattern
foreach ($username in $pattern)
{
$username = get-aduser -filter {name -eq $pattern}
if ($username -eq $pattern) {"User $fullname does not exist"}
else {"User $fullname exists"}
}
}
------------------------------------------------------
My CSV file looks ike this:
CN_FirstName_Lastname_UserPrincipalName_SamAccountName_password
Bill Brown_Bill_Brown_ubgg01_ubgg01_password
Bill Green_Bill_Green_ubgg02_ubgg02_password
Regardless of the fact that the user exists or not when I run the script I always get:
User Bill Brown found in AD
User Bill Green found in AD
Obviously there is something wrong but I don't understand what that is. This is my logic which in somewhere in practise it goes wrong.
- Import data from csv file.
- For each line in the csv file map the values to variables so that later can be used to create an non existing account
- store the $fullname of the user in a variable called ($pattern)
- then for each line in variable $pattern look if the $fullname appears in AD using get-aduser (I believe that's where I am wrong, i'm not sure whether you can use a foreach loop in this case.)
- if user exists print: user exists, otherwise print: user does not exist
Please help if you can. Thank you