Friday, April 19, 2024

Changing Multiple AD Passwords Using Powershell

I wrote this script a while back to change my password on multiple domains.

Make sure that all your passwords are synced between domains.   If the script fails, update your passwords manually, you don't want your accounts getting locked.

During execution, your passwords will be shown on the screen in clear text, so make sure no one is looking.

Here's the code:

$userName = "loginID"

$oldPassInput = Read-Host "Please enter your old password"
$oldPassword = ConvertTo-SecureString -AsPlainText $oldPassInput -Force

$newPassInput = Read-Host "Please enter your new password"
$newPassword = ConvertTo-SecureString -AsPlainText $newPassInput -Force

$domainArray = @("domain1", "domain2", "domain3", "domain4", "domain5")
## $domainArray = @("mpi")


foreach ($domain in $domainArray)
{

    # $User = $userName

    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "$domain\$userName", $oldPassword
    try {
        Get-Aduser $userName -Credential $Credential -Server $domain
        Write-Output "Login successful.  Old password is good on $domain."
        try {
            Set-ADAccountPassword -Credential $Credential -Server $domain -Identity $userName -OldPassword $oldPassword -NewPassword $newPassword
            Write-Output "Password changed on $domain"
        }
        catch {
            Write-Output "Error changing password on $domain. This could happen if your passwords are not synced, or expired, or new password doesn't meet security policies."
        }

    }
    catch {
        Write-Output "Login Failed.  Incorrect old password on $domain."

    }

}

No comments:

Post a Comment

Little script to see the backup history

 Today, I was teaching a co-worker how to create a copy only backup of a SQL Managed Instance database.  And I came up to use this script t...