@charles leon
Sure.
The password already includes numbers, special characters, lowercase and uppercase as you can see from the accounts.csv file generated by the script.
For the unique prefix 'PED', we'll replace the first part of Samaccountname i.e. $SamaccountnamePart1 in line number 9 with a hardcoded value:
$SamaccountnamePart1 = 'PED'
Now the script will look like this:
$n = 10 # Number of accounts required
$Path = 'CN=Users,DC=contoso,DC=com' # OU for the accounts
$UPNSuffix = '@contoso.com'
$OutputFile = 'Accounts.csv'
Clear-Content -Path $OutputFile -Confirm -ErrorAction SilentlyContinue
for($i=0; $i -lt $n; $i++) {
$SamaccountnamePart1 = 'PED'
$SamaccountnamePart2 = Get-Random -Minimum 100000 -Maximum 999999
$SamaccountnamePart3 = -join ((65..90) | Get-Random -Count 1 | ForEach-Object {[char]$_})
$Samaccountname = -join ($SamaccountnamePart1, $SamaccountnamePart2, $SamaccountnamePart3)
$password = -join ((33..126) | Get-Random -Count 12 | ForEach-Object {[char]$_})
$NewUserParams = @{
'SamAccountName' = $Samaccountname
'UserPrincipalName' = $Samaccountname + $UPNSuffix
'Name' = $Samaccountname
'GivenName' = $Samaccountname
'Surname' = $Samaccountname
'AccountPassword' = (ConvertTo-SecureString -String $password -AsPlainText -Force)
'Path' = $Path
'Enabled' = $True
}
try {
New-ADUser @NewUserParams -ErrorAction Stop # if successful, send created account data to a file
[PSCustomObject]@{
'SamAccountName' = $Samaccountname
'Password' = $Password
} | Export-Csv $OutputFile -Append -NoTypeInformation
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException]{
$i-- # Duplicate Samaccountname found, retry this one
continue
}
catch { # some other error occured when creating the account
Write-Output $PSITEM.Exception.Message
}
finally {
$Error.Clear()
}
}