Script to create a group service account in AD

Hi guys,
I would like to create a global security group that hold the servers accounts. Next, create a group manage account in AD.
I would need to check if the group name already exist before creating the group. The same check with the group service account. However, the script didn’t create the group nor did it create the service account after checking the group if exist. Appreciated if you can give me some tips . Thanks
Below is the script I’ve created:

$SvcName = Read-Host "Enter service account name"

$hostname = (Get-ADdomain).DNSRoot

$gname = Read-Host "Enter the group name"

$des = Read-Host "Enter group description"

$Path = Read-Host "Enter the path of the groups. Example:"CN=Computers,DC=busybox,DC=Local""

If(!(Get-ADgroup -identity "$gname")) {

    Write-host "Creating Security group $gname..." -ForegroundColor Green

    New-ADGroup -Name $gname -GroupCategory Security -GroupScope Global -Description "$des" -Path "$path"

} else {

    throw " The group $gname already exists"

}

if(!(Get-ADServiceAccount -identity $SvcName)) {

    New-ADServiceAccount -Name "$svcname" -DNSHostName "$hostname" -ManagedPasswordIntervalInDays 30 -PrincipalsAllowedToRetrieveManagedPassword "$gname"

} else {

    throw " The group managed service account $svcname already exists"

}

Instead of if statements you should use proper try catch blocks to determine if the names are already taken.

I’d expect this to be very error prone as it is very unlikely for anyone to correctly input an AD distinguished name. I’d recommend to read the desired OUs in advance and offer a limitted choice to the user to choose one from.

Regardless of that I’d probably create the group name and the service account name from the same base name to make their relation obvious. For example the group name SG for security group and SVA for service account and then followed by the base name. So you’d end up with SG_BaseName and SVA_BaseName.

Thank you. It is super helpful. I’ll take a look at try/catch method.