Hive
Hive

Reputation: 213

Powershell: Add user to groups from array

I am trying to write a PowerShell script that will create a user based off of Department and Position and add them to the AD groups specific to that position. I have a function that creates the new user and attempts to join the user to a list of groups in an array.

function CreateUser{
     $sam = "$first.$last";...;$pwd = ConvertTo-SecureString "password" -AsPlainText -Force
     New-ADUser -Company "MyCompany" -Department $dept -Description $desc -DisplayName $dname -EmailAddress $email -GivenName $first -Office $office -Path $path -SamAccountName $sam -Surname $last -UserPrincipalName $email
     foreach ($group in $groups) { if (Get-ADGroup $group) { Add-ADGroupMember $group $sam } }
     }

I have another bit of code that creates the $groups array

$positions = @()
if ($dept -eq "CSR") { $positions += "CSR Rep","CSR Lead","CSR Manager" }
if ($dept -eq "IT") { $positions += "Sysadmin","Netadmin","Sqladmin" }
...
$groups = @()
if ($position -eq "CSR Rep") { $groups += "group1","group2","group3",...,"groupN" }
if ($position -eq "CSR Lead") { $groups += "group1","group2","group3","group4",...,"groupN" }
if ($position -eq "CSR Manager") { $groups += "group1","group2","group3","group4","group5",...,"groupN" }
if ($position -eq "Sysadmin") { $groups += "group6","group7",...,"groupN" }
if ($position -eq "Netadmin") { $groups += "group7","group8","group9",...,"groupN" }
if ($position -eq "Sqladmin") { $groups += "group10","group11","group12",...,"groupN" }

After I've specified which department and position the groups array is created and I call the CreateUsers function but I get errors back like it is an empty array.

Is there something I am missing with trying to pass the parameters to the function or is there a better way to accomplish this task?
Any assistance would be greatly appreciated.

Upvotes: 0

Views: 3726

Answers (2)

Paul
Paul

Reputation: 5871

Since your code does not show the function call and your function does not have any parameters defined i assume you are not passing anything to it.

Here is how to use parameters with three example parameters, one of them a String[]:

function CreateUser{
     param(
     [parameter(Mandatory=$True)]
     [ValidateNotNullOrEmpty()]
     [string[]] $groups,
     [parameter(Mandatory=$True)]
     [ValidateNotNullOrEmpty()]
     [hashtable] $userInfo,
     [parameter(Mandatory=$True)]
     [ValidateNotNullOrEmpty()]
     [securestring] $pwd
     )

     New-ADUser -Company "MyCompany" -Department $userInfo.dept -Description $userInfo.desc -DisplayName $userInfo.dname -EmailAddress $userInfo.email -GivenName $userInfo.first -Office $userInfo.office -Path $userInfo.path -SamAccountName $userInfo.sam -Surname $userInfo.last -UserPrincipalName $userInfo.email
     foreach ($group in $groups) { if (Get-ADGroup $group) { Add-ADGroupMember $group $userInfo.sam } }
     }

To keep the number of parameters low i have consolidated the user info into a hashtable. Hashtables are key-value sets and can be created like this:

$userInfo = @{sam="sam"; dept="department"; desc="description"; ...}

To call your function correctly do something like this:

CreateUser -groups $groups -userInfo $userInfo -pwd $pwd

You can of course add more parameters. For documentation on possible definitions and validationmethods see Technet

Upvotes: 3

TheMadTechnician
TheMadTechnician

Reputation: 36322

If you're going to create functions that are going to be more than simple things that take parameters I would strongly suggest including parameters with them. Such as:

function CreateUser{
Param([Parameter(Position=0)][string]$First = $(throw "You must specify a first name"),
[Parameter(Position=1)][string]$Last = $(throw "You must specify a last name"),
[Parameter(Position=2)][string]$Desc = $(throw "You must specify a description"),
[Parameter(Position=3)][string]$Dept = $(throw "You must specify a department"),
[Parameter(Position=4)][string]$Office = $(throw "You must specify an office"),
[Parameter(Position=5)][string]$Password = $(throw "You must specify a password"),
[string[]]$Groups
)
     $sam = "$first.$last"
     $pwd = ConvertTo-SecureString $Password -AsPlainText -Force
     $email = "[email protected]"
     $dname = "$First $Last"
     $Path = "ou=$office,ou=Users,DN=company,DN=local"
     New-ADUser -Company "MyCompany" -Department $dept -Description $desc -DisplayName $dname -EmailAddress $email -GivenName $first -Office $office -Path $path -SamAccountName $sam -Surname $last -UserPrincipalName $email
     foreach ($group in $groups) { if (Get-ADGroup $group) { Add-ADGroupMember $group $sam } }
}

Then when you call the function you do it as such:

CreateUser "Jim" "Kirk" "Captain Extraordinaire" "Space" "$uper$ecret123" @("ExploreNewWorlds","WhereNoManHasGone")

Or you can specify arguments by name:

CreateUser -First "Jim" -Last "Kirk" -Desc "Captain Extraordinaire" -Dept "Space" -Password "$uper$ecret123" -Groups @("ExploreNewWorlds","WhereNoManHasGone")

...and while I got caught up in work trying to post this Paul beat me to it. Nice work Paul!

Edit: On a side note, I would like to introduce you to the Switch cmdlet. I think you would benefit greatly from it. While your several If statements probably do work, consider this:

Switch($position){
    "CSR Rep" { $groups += "group1","group2","group3",...,"groupN";continue }
    "CSR Lead" { $groups += "group1","group2","group3","group4",...,"groupN";continue }
    "CSR Manager" { $groups += "group1","group2","group3","group4","group5",...,"groupN";continue }
    "Sysadmin" { $groups += "group6","group7",...,"groupN";continue }
    "Netadmin" { $groups += "group7","group8","group9",...,"groupN";continue }
    "Sqladmin" { $groups += "group10","group11","group12",...,"groupN" }
}

That's simplistic, and in your case may not offer too much in performance improvement, but Switch offers a cleaner solution, and improved performance over several If statements. It also allows for more logic such as:

Switch($position){
    {$_ -match "CSR" } { $groups += "group1", "group2" }
    {$_ -match "CSR" -and -not $_ -match "Rep"} { $groups += "group3","Group4" }
}

That would add groups 1 and 2 for all CSR, and only Leads and Managers get groups 3 and 4. Anyway, just something to consider.

Upvotes: 2

Related Questions