I have the following code with some setup at the top, and code pulled from within a loop body below:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$DIR_SVCS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('domain')
## Other stuff...
## usersOU is set to the domain of the users (...,OU=users,dc=<domain>...)
Search-ADAccount -LockedOut -SearchBase $usersOU | Unlock-ADAccount
## Loop code...
$userID = 'myuser'
$password = 'TempPa$$w0rd'
$SecurePW = ConvertTo-SecureString ($password) -AsPlainText -Force
Set-ADAccountPassword $userID -Reset -NewPassword $SecurePW | Out-Null
if ((-Not $?) -or ($LASTEXITCODE -gt 0)) {
Throw "ERROR with Set-ADAccountPassword exit code $LASTEXITCODE on $userID"
}
if ($DIR_SVCS.ValidateCredentials($userID, $password)) {
Write-Host "Validated new account password: $userID"
} else {
Write-Host "FAILED validation of new account password: $userID"
}
This is executed across an array of users and passwords, and the output leaves me scratching my head:
Validated new account password: user1
FAILED validation of new account password: user2
FAILED validation of new account password: user3
Validated new account password: user4
FAILED validation of new account password: user5
...
I can see no indication of why this fails on some and succeeds on others. All of the users being modified exist in the "$usersOU" which gets unlocked above, but I would expect an error to be thrown after the 'Set-ADAccountPassword' call, or all of the validation calls to succeed...
Any help understanding what's going on here would be appreciated!
This is typically seen while querying active directory from both ActiveDirectory module and .NET in a multi domain controller environment. This can be mitigated by ensuring that both are speaking to the same server, the easiest way would probably be to use the "ConnectedServer" property from $DIR_SVCS together with Search-ADAccount
For an example:
Search-ADAccount -LockedOut -SearchBase $usersOU -Server $DIR_SVCS.ConnectedServer | Unlock-ADAccount