SQL, PowerShell and Adding a User to an AD Group

Welcome Forums General PowerShell Q&A SQL, PowerShell and Adding a User to an AD Group

Viewing 1 reply thread
  • Author
    Posts
    • #258119
      Participant
      Topics: 1
      Replies: 0
      Points: 11
      Rank: Member

      Hi All:

      I’m 95% done on a project but am struggling with the final piece. I only took one coding class as an undergrad and I don’t have a lot of experience in it. Scenario: users fill out a webform on our intranet when a new hire arrives. This data goes into an SQL server. I have the code written which:

      1. asks me via console input for the user last name. I type in the last name and hit enter.
      2. it then queries the sql database and returns the user in question (query only goes back 30 days to prevent retrieving an old record of someone w the same last name).
      3. AD user is created in an OU I specify from a tree.
      4. Exchange account is created.

      I’m trying to finish the code that will add the newly created user to AD groups. I’ve gotten a list box with a variable early on in the code that lists all our user groups. This selection is stored into a variable ($thegroups) successfully. I need to try and pass the samaccount parameter onto the Add-ADGroupMember command.

      Invoke-Sqlcmd -ServerInstance mysqlservername -Database mydatabasename -Query "SELECT * FROM dbo.NewUserForm WHERE Emp_LastName= '$MYVAR1' AND DateReceived >= DATEADD(day, -30, GETDATE())" |

      select @{l='Name';e={$_.Emp_FirstName+" "+$_.Emp_LastName}},
      @{l='SamAccountName';e={$_.Emp_FirstName.tolower().substring(0,1)+$_.Emp_LastName.tolower()}},
      @{l='UserPrincipalName';e={$_.Emp_FirstName.tolower().substring(0,1)+$_.Emp_LastName.tolower()+"@contoso.local"}},
      @{l='DisplayName';e={$_.Emp_FirstName+" "+$_.Emp_LastName}},
      @{l='GivenName';e={$_.Emp_FirstName}},
      @{l='Surname';e={$_.Emp_LastName}},
      @{l='Title' ;e={$_.JobTitle}},
      @{l='OfficePhone';e={$_.PhoneNumber}} |

      New-ADUser -Path "$($xyy)" -Country "us" -ChangePasswordAtLogon $True -State "WA" -City "Contosoville" -StreetAddress "$($theaddress)" -PassThru |
      select Name, SamAccountName, UserPrincipalName

      Add-ADGroupMember -members SamAccountName -Identity $thegroups

      I know I am close. At least I think I am. Any help would be appreciated!

    • #258134
      Participant
      Topics: 16
      Replies: 1794
      Points: 3,300
      Helping Hand
      Rank: Community Hero

      Only portions of the code are provided, but you should be able to do something like this:

Viewing 1 reply thread
  • You must be logged in to reply to this topic.