0

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.

5
  • please show us how you call the function and post the Error Commented Oct 22, 2014 at 0:40
  • originally I was just calling the function like 'CreateUser' without specifying any params to go with it. things like $first and $last were automatically being populated and I didn't think much of it. I did try to specify $groups as a param, but I tried [array]. the error I get is: Get-ADGroup: Cannot validate argument on parameter 'Identity'. The argument is null. Supply a non-null argument and try the command again. At usermanagement.ps1:131 char:19 + if (Get-ADGroup <<<< $group){ Add-ADGroupMember $group $sam }} Commented Oct 22, 2014 at 14:48
  • this will only work if the variables you use in the function are declared beforehand, i would advise you to allways use parameters if you want to be safe. For an example on how to declare the parameter for $groups correctly see the first parameter-declaration in my answer Commented Oct 22, 2014 at 14:51
  • I have add the params that you have above and after some troubleshooting have discovered that for some reason the variable that I have storing the groups get erased before it runs to create the user. Seems that I have some bug I need to fix before I can get it to create a user. Commented Oct 22, 2014 at 15:37
  • I was able to get the groups in to the variable and everything is working like a charm. Thank you for the clearification with calling functions. Commented Oct 22, 2014 at 19:54

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help. I will try to create a hashtable to be able to pass these parameters through and see if that works.
2

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.

1 Comment

Thank you for you help. I like the switch idea. I'll try it out with passing parameters to the function and let you know how it goes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.