adding users to group

by Nidhin CK at 2013-01-09 17:53:39

Hi Experts,

I’m using the below screen to add users to group. Input is taking from csv file. below script is working fine

Import-Module activedirectory
$cre = Get-Credential
$server = Read-Host "Type server FQDN"
Import-Csv c:\groups.csv | % {Get-ADGroup -Identity $.group | Add-ADGroupMember -Members $.user -Server $server -Credential $cre | Export-Csv c:\groupoutput.csv}

CSV file format:-

Problem is when I’m validating the existance of group or user objects in Active Directory. I used below query to check whether the mentioned groups in csv is present in AD or not.
But im not getting the expected answer :frowning: I mean even though if there is no gtroup object present in ad the code is directly going to else condition

Import-Module activedirectory
$cre = Get-Credential
$server = Read-Host "server name"
$grp = Import-Csv c:\groups.csv | % {Get-ADGroup -Identity $.group}
if ($grp -eq $null) {Write-Host "No such groups in ad"}else{
Import-Csv c:\groups.csv | % {Get-ADGroup -Identity $
.group | Add-ADGroupMember -Members $_.user -Server $server -Credential $cre | Export-Csv c:\groupoutput.csv}}
by kittH at 2013-01-10 05:20:30
It looks like you’re not checking each group, you’re just checking if any of the groups exist, and if so, continue with all of the rows in the spreadsheet.

I think you’ll have to do a more granular check, depending on how many rows you have and how many unique groups you’re trying to add users to there are a couple of ways.

The most simple would just be to check on each row

$Results = @()
Foreach ($Row in (Import-Csv C:\groups.csv)){
If(Get-ADGroup -Identity $Row.Group){
Get-ADGroup -Identity $ | Add-ADGroupMember -Members $Row.user -Server $server -Credential $cre
$Results += $Row}}
$Results | Export-Csv C]

This is untested and I copied most of the actions from your script so please test, but it will check on each row if the group exists, and if so add that member to the group. Since it looked like you wanted output at the end it also has a "results" array that it builds from all of the users that pass the if condition. One thing it does not do is test if the user is already a member of the group before adding them.