0

I'm writing a script in PowerShell to automate creation of AD users. One of the conditions I use is to check if the user already exists, then to Write-Host "User exists" and move to the next element in the array. However, when I run the script, it gives me an odd behavior. I'll put the code then explain what happens when I put in breakpoints.

$MACList = Get-Content $Path\MACs.txt
foreach ($MAC in $MACList){
   $MABName = Get-ADUser $MAC
   if ($MABName -ne $null) {
      Write-Host "MAB already exists, moving to next"
   } else {
      # create the new user
   }

When I run the script with breakpoints I can see that $MACList contains the MACs in the file. When I move to the next step, I can see that $MAC contains each element as I traverse the $MACList array. When it gets to the $MABName line, $MAC indeed contains a MAC address, so it should go find if I have that user and set $MABName to that user. It seems to keep the same value if the Get-User cmdlet doesn't return an object. Any ideas on why this might happen?

1 Answer 1

1

Get-ADUser throws an error for non-existing users, so the variable retains its previous value. Use the -Filter parameter to avoid this issue:

$MABName = Get-ADUser -Filter "SamAccountName -eq '$MAC'"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.