Multiple (gMSA) Accounts



I am using a script to create gMSA accounts, I like to ask some help for the membershop and principle section.

From a csv I use the accountnames, principle and ADgroupnames. per gMSA Account
When I run the script the accounts are created only with all of Principles and Adgroups.
IN stead of just the first Gmsa with the principles and adgroups in line1, it gets also the principles and Adgroups on line 2 and 3 in the csv.

This makes sense because these are collected in a array, only I don’t know (yet) how to make sure that just the neccesary principals and ADgroups are added to the correct account.


GMSA Domain Description Wnr Principal Adgroup Aanvrager Mail
saccadviesapit w1223 Princ123 Pieter Bakker|
saccadviesapia w1223 Princ123 Pieter Bakker|
saccadviesapip w1223 Princ123 Pieter Bakker|


#import the information from a csv 
$Import = import-csv 'P:\Users\PieterB\Scripts\CSV\New-GMSA Account.csv' -Delimiter ";"
$domain = $Import.Domain[1]
$DC = Get-ADDomainController -server $domain -Filter * | ? {$_.OperationMasterRoles -contains 'infrastructuremaster'} | Select -exp Hostname

$ComputerObjects = @()
$LocalAdminGroup = @()

    Foreach ($Entry in $Import)
        $Svr = $Entry.principal -split(',')
        $ComputerObject     = $svr | Get-ADComputer  -Server $entry.Domain |select DistinguishedName
        #$ComputerObjects  += $ComputerObject
        $ADG = $Entry.adgroup -split(',')
        $ADG | Get-adgroup  -Server $domain |select DistinguishedName

    $Gmsa= foreach($account in $Import){
        $Data = @{
        Name = $account.Gmsa
        Server =$DC
        Displayname = $
        Description = $account.description + $account.wnr
        DNSHostname = $ + $account.domain
        KerberosEncryptionType = "AES128,AES256"
        PrincipalsAllowedToRetrieveManagedPassword = $computerobject.DistinguishedName
        Enabled = $true
        Passthru = $true
        Whatif = $false
        New-ADServiceAccount @Data    
         #end foreach

#add GMSA to a local administrator group

 Foreach ($entry in $import){
    $Sam = Get-ADServiceAccount $entry.gmsa -server $entry.Domain |select -ExpandProperty 
    $ADG = $entry.adgroup -split(',')
    add-ADPrincipalGroupMembership $Sam -Server $entry.domain -MemberOf $ADG