Photo by Somchai Kongkamsri on Pexels.com

You can use this script to create service account with :

  • Certain Naming Convention.
  • 18 Character long password.
  • Add account to specific AD Groups

This script can be become your baseline to create/add more parameters. Before you use this script, please update

  • Line 22 with your company’s UPN domain.
  • Line 24 with the OU, where these accounts will be created.
  • Line 32 & 33 with AD group, where you want to add newly create account.
Write-Host "Welcome to Service Account Creation" -ForegroundColor Green
Write-Host "Type Service Account Name in SVC-Purpose-Service (SVC-Log-SQL) Format and Try Keep it under 20 Character" -ForegroundColor Green
$name = Read-Host "Type Service Account Name"

# Generate a random password
$rand = New-Object System.Random
$userpassword = $null
1..2 | Foreach { $userpassword += [char] $rand.Next(48,57) }
1..2 | Foreach { $userpassword += [char] '(' }
1..2 | Foreach { $userpassword += [char] '$' }
1..2 | Foreach { $userpassword += [char] $rand.Next(65,90) }
1..2 | Foreach { $userpassword += [char] '#' }
1..8 | Foreach { $userpassword += [char] $rand.Next(97,122) }

# Display the generated password
Write-Host
Write-Host ($userpassword + " is the current password of " + $name + ".") -ForegroundColor Yellow
Write-Host

# Create the service account in AD
$pass = ConvertTo-SecureString -AsPlainText $userpassword -Force
$upn = $Name + "@learntecufuture.com"
try {
    New-ADUser -Name $Name -GivenName $Name -Surname $Name -SamAccountName $Name -UserPrincipalName $upn -DisplayName $name -Path "OU=SVCs,DC=learntecufuture,DC=com" -AccountPassword $pass -Enabled $true -ErrorAction Stop
    Write-Host ($name + " has been created in AD.") -ForegroundColor Yellow
} catch {
    Write-Host "Error creating the service account: $($_.Exception.Message)" -ForegroundColor Red
}

# Add the service account to security groups
try {
    Add-ADGroupMember -Identity AllSvcs -Members $name -Confirm:$false -ErrorAction Stop
    Add-ADGroupMember -Identity ControlledUsers -Members $name -Confirm:$false -ErrorAction Stop
    Write-Host ($name + " has been added to ControlledUsers and AllSvcs.") -ForegroundColor Yellow
} catch {
    Write-Host "Error adding the service account to security groups: $($_.Exception.Message)" -ForegroundColor Red
}

Thanks you for reading !

Advertisement