Monday, August 16, 2010

Powershell: Force AD Users to Reset Password

There are times when going into ADUC and modifying a bunch of users to have their password change on next logon is either a) too much hassle or b) needs to be a specific time.  By using powershell and Quests ActiveRoles modules, we can create a fairly simple script to do so.

When running this script, there are a few things that can go wrong – for example a user might be set to ‘can not change password’.  So there are a few ways to catch this, my personal favourite is by raising an event log error and having our management software pick up on the event id.

Setting the Variables
First thing we need to do is to set some variables, this script assuming we want to force the reset for all users in a specified OU – this does propagate down to child OU’s as well.

#------- Assign Variables -------#
Add-PSSnapin Quest.ActiveRoles.ADManagement
$OUvar = $args[0]
$OU = Get-QADObject | ? { ($_.Type -eq "organizationalUnit") -and ($_.Name -eq $OUvar) }
if (!$OU) {
write-host "No Organizational Unit with the name of "+$OUvar+" could be found."
break
}else {
$Users = Get-QADUser -SearchRoot $OU.DN
if (!$Users) { write-host "No users found in OU "+$OU.DN+"."
else { write.host "Successfully harvested the following users from OU "+$OU.DN+" `n "+$Users
}
#------- ######## -------#



So basically here we are accepting a command line variable as the OU to find the users in. There is a little error checking here as well to make sure we have some users to apply this too.




Forcing the Change
Here is the real meat and potatoes of this script, it also includes some basic error checking and makes sure that all users that were told to flag were indeed flagged.

#------- Force Password Change On Next Logon -------#
ForEach ($User in $Users) {
Set-QADUser $User -PasswordNeverExpires $false -UserMustChangePassword $true
$UsersVerified = Get-QADUser -SearchRoot $OU.DN | ? { $_.UserMustChangePassword }
}
if ($Users.count -ne $UsersVerified.count) {
$UsersDif = compare $Users $UsersVerified
write-host "Not all users were modified, the following users were not affected. `n "
+$UsersDif.inputobject.logonname
}else { write-host "Users were successfuly set to change password on next logon" }
}
#------- ######## -------#

No comments:

Post a Comment