Add User CSV to static groups

Sorry everyone; I know something so simple must be here already, but I can’t see it :frowning:

I have CSV and I want to add it to a set of groups as part of a larger onboarding script. I want to know if I can just add it like this or I need to list everything separately?

#Function SetGroups ($sam)
{
Try
{
Get-ADUser $sam | Add-ADGroupMember -Identity “Group1,Group2,Group3” -Members $sam
$OutPut = "Success: Added $sam to Correct Groups "
Write-Host $OutPut -ForegroundColor Green
WriteToLog $LogFile $OutPut
}
Catch
{
$OutPut = "FAIL: DID NOT Set $sam in to the Correct Groups"
Write-Host $OutPut -ForegroundColor Red
WriteToLog $LogFile $OutPut
}
}#end Fn

Can you add the part where you read the data from CSV too ? it will make folks here to propose a better solution.

There are many problems with this approach:

  1. You have not set the ErrorAction to Stop, so the Try\Catch logic will not work
  2. You have hard-coded groups in the script, so it only adds specific groups. If there is a param, then it provides flexibility for Role-Based Access Control after you build a generic user
  3. If you do set an ErrorAction, then anything can break the process. If you find the user and the first group isn't found, it will never process the other two groups

You function work more like pseudo code:

$user = Get-ADUser -Filter ...

if ($user) {
    foreach ($grp in $Group) {
        try {
            Add-ADGroupMember -Identity $grp -Members $user -ErrorAction Stop
        }
        catch {
            $_
        }
    }
}

As kvprasoon said, this may not be the best solution, but we would need to see the entire script. This wrapper is basically the same thing as Add-ADGroupMember, so you are not really gaining anything by putting a wrapper around it.

I have one question.

I written a script for addition request in ad group.

Import-module ActiveDirectory
$users=import-csv c:\users.csv
$groups=‘group1’, ‘group2’, ‘group3’
For each ($user in $users) {Ada-adgroupmember -identity $groups -members $user}

Please validate my script and give me a suggestion. While ran the script getting error from -identity line.

[quote quote=200498]I have one question

Please validate my script and give me a suggestion. While ran the script getting error from -identity line.[/quote]

Please do not hijack other peoples threads. If you have a question create a new post for yourself and place a link to the other post if it’s related and helpful for your question.

Please (re-)read the very first pinned post of this forum Read Me Before Posting! You’ll be Glad You Did!.

If you get error messages you should post them along with the code - both formatted as code using the code tag button (“PRE”). Thanks