Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Adding users to groups from CSV file - skipping blank fields

$
0
0

Hi,

I have the following script:

$userList = Import-Csv "newUsers.csv"
$groups = $userList | Get-Member | where { $_.Name -like "Group*" } | select -Property Name

ForEach ($user in $userList) 
{
    Write-Verbose "Creating user $($user."Logon Username")"
    $params = @{
        Name = $user."Display Name"
        ParentContainer = $user."Container"
        SamAccountName = $user."Logon Username"
        UserPassword = 'p@SSword'
        FirstName = $user."Prenume"
        LastName = $user."Nume"
        Description = $user."Departament"
        UserPrincipalName = $user."Logon Username" + "@info.rusu.lab"
        DisplayName = $user."Display Name" 
    }

    New-QADUser @params
    Set-QADUser -identity $user."Logon Username" -UserMustChangePassword $true

    
    foreach ($group in $groups)
    { 
        $groupName = $group | select -ExpandProperty Name
        if ($($user.$groupName) -ne "")
        {
            Write-Verbose "Adding user $($user."Logon Username") to $groupName"
            Add-QADGroupMember -identity $groupName -Member $user."Logon Username" 
            
        }
    }
    $VerbosePreference = "Continue"
}

In have the  CSV file with 4 columns named Group, Group2,Group3 and Group4. If I run the script, the users are created corectly, but they are added only in the first group, after that, the following error is displayed:

Add-QADGroupMember : Cannot resolve directory object for the given identity: 'Group2'.
At C:\PS Work\Disertatie\Scripts\Add users\new example of adding user.ps1:29 char:13
+             Add-QADGroupMember -identity $groupName -Member $user."Logon Usernam ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-QADGroupMember], ObjectNotFoundException
    + FullyQualifiedErrorId : Quest.ActiveRoles.ArsPowerShellSnapIn.DirectoryAccess.ObjectNotFoundException,Quest.ActiveRoles.ArsPow 
   erShellSnapIn.Commands.AddGroupMemberCmdlet2

I need to mention that I am a beginner in PS.


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>