Script to create AD User account, AD Group and add user to group

This topic contains 2 replies, has 2 voices, and was last updated by  Nathan W 2 years, 8 months ago.

  • Author
  • #20897

    Nathan W

    I am new to powershell and I am trying to write a script that will create an AD user account, Create an AD security group then add that user account to the AD group.
    Here is what I have so far and I seem to not have it quite right.

    $GroupVar=Read-Host "Enter Local Admin Group name"
    $UserVar=Read-Host "Enter Local Admin User ID"
    $UserGivenNameVar=Read-Host "Enter Users First Name"
    $UserSurNameVar=Read-Host "Enter Users Last Name"
    New-ADUser -Name $UserVar -AccountPassword password -ChangePasswordAtLogon 1 -GivenName $UserGivenNameVar -Surname $UserSurNameVar -DisplayName "$UserGivenNameVar $UserSurNameVar – Local Admin" -Path "CN=OU1,CN=OU Number 2,DC=child,dc=domain,DC=com"
    New-ADGroup -Name "$GroupVar" -GroupScope Global -GroupCategory Security -Path CN=OU1,CN=OU Number 2,DC=child,DC=domain,DC=com
    Add-ADGroupMember -Identity $GroupVar -Members $UserVar

    Thanks for the assistance

  • #20902


    There's a few problems here. One, you cannot provide the New-ADUser cmdlet's -AccountPassword parameter a standard string. Instead, you must use the ConvertTo-SecureString cmdlet to first convert your string before using it as the parameter's value. Use this instead: ...-AccountName (ConvertTo-SecureString -AsPlainText 'password' -Force)... The parenthesis indicate to first run the ConvertTo-SecureString, before applying it as the value for that parameter.

    Second, you need to correct your DistingushedName (DN) paths and ensure they are enclosed in quotes. I'd recommend single quotes in this instance. Based on your code, I would guess you meant to write those as 'OU=OU1,OU=OU Number 2,DC=child,DC=domain,DC=com'. It's possible, however, that you're using really generic names and therefore I can't determine if you're trying to add your user and group to an OU (an Organization Unit) or to a Container (think: Builtin, Computers, Users). If you were creating a DN for the Users Container, then you would use this: 'CN=Users,DC=child,DC=domain,DC=com'.

    And finally, as you get more and more comfortable with PowerShell, you'll want to strive for some error checking (user presses enter without entering any data), checking if a user or group already exists before you try and create it, etc.

  • #20908

    Nathan W

    Thanks for the info.
    It was very helpful and I was able to get the script up and running.

You must be logged in to reply to this topic.