I used this Powershell Script to onboard user to create password and enable account. I have no idea why it's randomly get the error An internal error occurred HRESULT: [-2146233087] . When I manually re-try, it's successful. So now I would like to auto re-try 5 times automatically.
Can anyone help on this?
Script
function Get-RandomCharacters($length, $characters) {
$random = 1..$length | ForEach-Object { Get-Random -Maximum
$characters.length }
$private:ofs = ""
return [String]$characters[$random]
}
function ScrambleString([string]$inputString) {
$characterArray = $inputString.ToCharArray()
$scrambledStringArray = $characterArray | Get-Random -Count
$characterArray.Length
$outputString = -join $scrambledStringArray
return $outputString
}
Start-Sleep -s 30
$GC = "ldap.abc.com:3268"
$DC = "abc.com"
$user = get-aduser -Identity $sam -Properties userPrincipalName, sAMAccountName -Server $GC
$upn = $user.userPrincipalName
$password = $null
$password = Get-RandomCharacters -length 5 -characters 'abcdefghiklmnoprstuvwxyz'
$password += Get-RandomCharacters -length 1 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
$password += Get-RandomCharacters -length 1 -characters '1234567890'
$password += Get-RandomCharacters -length 1 -characters '!@#$%^*()+='
$password = ScrambleString $password
$sam = $user.sAMAccountName
try {
Set-ADAccountPassword -Identity $sam -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $password -Force) -Server $dc
Set-ADUser -Identity $sam -Server $DC -ChangePasswordAtLogon $true
Enable-ADAccount $user -Server $DC
$output = @{Password = $Password; AccountName = $UPN } | convertTo-JSON -compress; $output
}
catch {
Write-Error "Unable to set password, $error"
}
I tried to manually re-run the script before, it's workable. What I expect is to auto retry 5 times if failure., so it will reduce my workload.