Good afternoon! Hope everyone's getting settled in with warm drinks and snowshoes.
I am working on a user creation script for AD and came across some curious behaviour. The goal here is to check if the person's SAMID already exists, and if it does, to append "1" to the SAMID.
For example, let's use "Jaina Proudmoore" as our user.
import-csv $inputCSV | foreach {
$FullName = $_.FullName
$company = $_.Company
$Givenname = $fullname.Split(" ")[0]
$Surname = $fullname.split(" ")[1]
$firstInitial = ($fullname.substring(0,1)).ToLower()
$surnameLower = $surname.ToLower()
$GivennameLower = $Givenname.ToLower()
$samid = $firstInitial + $surnameLower
$samidcheck = get-aduser $samid
if ($samid -ne $null) {
$samid = $samid + 1
}
$Description = "Created By NewUserCreation Script $DateFormat"
$global:Department = $_.Department
$Title = $_.Title
$Office = $_.Office
$StreetAddress = $_.StreetAddress
$PostalCode = $_.PostalCode
$ManagerFullName = $_.Manager
$ManagerDN = (get-aduser -filter 'Name -like $ManagerFullName').DistinguishedName
$Country = "CA"
$co = "Canada"
$OfficePhone = $_.OfficePhone
$MobilePhone = $_.MobilePhone
$countryCode = "124"
$City = $_.Location
$GroupSourceUser = $_.GroupSourceUser
$GroupSourceUserDN = (get-aduser -filter "Name -like '$GroupSourceUser'").DistinguishedName
$ADUserCheck = get-aduser -Filter 'Name -like $FullName' -ErrorAction SilentlyContinue
In this case, the SAMID check should give me:
$samidcheck = get-aduser jproudmoore
If I were to execute this manually:
get-aduser : Cannot find an object with identity: 'jproudmoore' under: 'DC=home,DC=local'.
At line:1 char:1
+ get-aduser jproudmoore
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (jproudmoore:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
If I understand this correctly, it means "user wasn't found". So therefore, my SAMID should be created as "jproudmoore". However, the script creates "jproudmoore1", as if it were detecting the output as NOT null.
if ($samid -ne $null) {
Since there was an object not found error, I would assume that the output is indeed not equal to null, and therefore:
$samid = $samid + 1
}
What am I missing here? I feel like it's something obvious.
Thanks in advance for your time and have a fabulous week!
- EDIT -
I also tried this manually:
$test = get-aduser jproudmoore
if (!$test) {write-host "variable is null"}
PS > variable is null
If I'm correct here, then that would mean the SAMID check should not have appended "1".