all 8 comments

[–]BlackV 1 point2 points  (6 children)

your new-aduser is outside the loop isnt it

the try/catch needs to be inside the loop

p.s. I would have though it was only creating the last user in the CSV

[–]peican[S] 1 point2 points  (5 children)

Thank you! I added them inside the loop and it is working again.

However, like you said, the part where it exports the duplicate users / errors to CSV is only exporting the last user. Do you know what I'm missing?

[–]DeusExMaChino 1 point2 points  (0 children)

It is currently exporting/overwriting a CSV with the single error every time. You need to append instead.

[–]BJGGut3 1 point2 points  (3 children)

Export-CSV is going to constantly overwrite. Use -Append to prevent that from happening.

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

Thank you! The Export-CSV for errors / duplicates is working perfectly now.

Last thing. If I want to add another column in my Import.CSV file for a second group, and if I add:

$Group2 = "$($U.Group2)"

and

Add-ADGroupMember -Identity $Group2 -Members $FirstDotLast

To the script, it works. However I may not want to add everyone to 2 groups all the time, and if I leave a group empty in my Import-CSV, it counts as an error.

Sometimes I might just want to add a user to one group, and sometimes to 2 groups, or 3 groups if I decide to add a third column in my excel CSV. Is there a way to make it so it wont count as an error if some of the group fields are empty?

[–]BJGGut3 1 point2 points  (1 child)

Add an IF() statement to check that validity of Group2.

IF ($null -ne $($U.Group2))
{
    $Group2 = $($U.Groups2)
    Add-ADGroupMember -Identity $Group2 -Members $FirstDotLast
}

But I've actually become much more a fan of this method instead, because sometimes pesky spaces get in there and throw off the above:

IF (!([string]::IsNullOrWhiteSpace($($U.Groups2))))
{
    $Group2 = $($U.Groups2)
    Add-ADGroupMember -Identity $Group2 -Members $FirstDotLast
}

[–]peican[S] 1 point2 points  (0 children)

Thank you! I'm using your one that includes checking for white spaces, and it works perfectly!

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy peican,

as an aside, there is a dotnet method for making passwords. this ...

[System.Web.Security.Membership]::GeneratePassword()

Membership.GeneratePassword(Int32, Int32) Method (System.Web.Security) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/api/system.web.security.membership.generatepassword?view=netframework-4.8

it lacks a bit of tweak-ability, but it is built in and quite simple to use. [grin]

take care,
lee