Multiple (gMSA) Accounts

Hello,

2023-01-24T23:00:00Z

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.

CSV :

GMSA Domain Description Wnr Principal Adgroup Aanvrager Mail
saccadviesapit gmsa.eu dexr.xxx w1223 Princ123 Pieter Bakker Pieter@domain.eu|
saccadviesapia gmsa.eu dexr.xxx w1223 Princ123 Pieter Bakker Pieter@domain.eu|
saccadviesapip gmsa.eu dexr.xxx w1223 Princ123 Pieter Bakker Pieter@domain.eu|

New-Gmsa.ps1:

#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 = $account.name
        Description = $account.description + $account.wnr
        DNSHostname = $account.name + $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 
samaccountname
    $ADG = $entry.adgroup -split(',')
    add-ADPrincipalGroupMembership $Sam -Server $entry.domain -MemberOf $ADG
    }