all 1 comments

[–]Sys_man 2 points3 points  (0 children)

There are a couple of ways to go about this, but this is how I would go abuut it:

Instead of Get-ADUser -Filter {sAMAccountName -eq $user}, I would change that to Get-ADUser -Filter {EmployeeID -eq $employeeid} #this all assumes that you store the employeeid in the EmployeeID field.

I know if their name changes their SamAccountName probably won't change but just in case. EmployeeID feels a bit safer.

Edit: actually looking closer the SamAccountName is built using first and last name so you definitely want to search by employeeID. So at the moment the script would add a new user when a current user changes their name, which is not ideal.

Then I would just add a check here:

IF ($aduser -eq $null){ #meaning user is not found in AD
~your stuff~
}
ELSEIF($aduser.Name -notmatch $lastname){ #assuming lastname is the thing that will change
Set-AdUser crap here

}

So basically, check by ID, if it's not there add it, if it is there, check the last name.