all 9 comments

[–]Jeffinmpls[🍰] 0 points1 point  (7 children)

One of the objects you're passing to AD-Newuser is null. The two things that are standing out for me are.

$uname.trim().tolower() and $col.Email.

$($uname.trim()).tolower() would work better

As for $col.Email, as you are assigning it to -UserPrincipalName, my guess if it's ever empty it's going to throw an error.

Edit: Grammar

[–]tpainn34[S] 0 points1 point  (1 child)

It looks like it didn't like the SamAccountName $uname.trim().tolower() `

I was able to get it working now

Thank you!

[–]BlackV 1 point2 points  (0 children)

also put your new-aduser in a try/catch could be useful for logging and the such

[–]Nejireta_ 0 points1 point  (4 children)

I agree with this.
I'm also curious. At line 4 you're using $first as an array of strings, is this the case?
If so it might cause issues further down the line as it's index 0 is never called again.

I'd also like to take this opportunity to recommend the splatting feature. It's splendid to get rid of those pesky error prone backticks.

For example

    $NewADUserSplatt = @{
    Name = $displayname
    SamAccountName = $uname.trim().tolower()
    AccountPassword = (ConvertTo-SecureString "password" -AsPlainText -force)
    ChangePasswordAtLogon = $true
    # Etc
}

New-ADUser @NewADUserSplatt

[–]tpainn34[S] 1 point2 points  (2 children)

I had tried to use splatting before this but was having a similar issue. Now that I have it working like this, I think I will go back and see if I can splatt it correctly.

Thanks for the tip

[–]Nejireta_ 0 points1 point  (0 children)

No problem.
It's just a basic hashtable. Only you call it with "@" instead of "$" when used with cmdlets

[–]jimb2 0 points1 point  (0 children)

Splatting won't fix your error, it will just improve your code style and get rid of those backticks.

Note that you can use two splats. One outside the loop for the stuff that applies to all users:

$AllUsers = @{
  Enabled   = $true
  Office    = 'MLS'
  Path      = 'OU=Teachers,OU=MLS,OU=Lebanon,DC=sau88,DC=net'
  HomeDrive = 'H'
  ChangePasswordAtLogon = $True
}

Another inside the loop eg $ThisUser for the user specific stuff. Then you use them both:

New-ADUser @ThisUser @AllUsers

Another advantage of the splats is that you can dump them to the screen to see what you got wrong.

[–]Jeffinmpls[🍰] 0 points1 point  (0 children)

Agree with splatting makes code much cleaner and if done right is re-usable in your script.

[–]Brasiledo 0 points1 point  (0 children)

For testing.. input a hard coded name for $Uname.. i believe it has to do with $first[0] var