Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Function to generate password
- Function Get-Password ($length=10)
- {
- Add-Type -AssemblyName System.Web
- $password = [System.Web.Security.Membership]::GeneratePassword($length,4)
- return $password
- }
- Function Secure-Password
- {
- $password= Read-Host -AsSecureString "Enter your password"
- $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
- $password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
- return $password
- }
- #Define user variables
- $userName=$env:USERNAME
- $currentPassword=Secure-Password
- #$preferredPassword=$true #comment out if your current password is your preferred one
- $preferredPassword=$currentPassword
- $passwordHistory=24
- #Initialize the user context
- Add-Type -AssemblyName System.DirectoryServices.AccountManagement
- $principalContext=New-Object System.DirectoryServices.AccountManagement.PrincipalContext("Domain")
- $userPrincipal=[System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($principalContext,"SamAccountName", $userName)
- $passwordList=@{}
- for($i=0;$i-le $passwordHistory;$i++)
- {
- $newPassword=Get-Password
- Write-Host "`nAttemping password change number"$i
- $passwordList.Add("Password-$i",$newPassword)
- try
- {
- $userPrincipal.ChangePassword($currentPassword, $newPassword)
- }
- catch [PasswordException]
- {
- $Error[0].Exception.Message
- }
- Write-Host "Password Changed successfuly"
- $currentPassword = $newPassword
- Sleep -Milliseconds 1500
- }
- if($preferredPassword -eq $true)
- {
- $newPassword=Secure-Password
- $userPrincipal.ChangePassword($currentPassword, $newPassword)
- }
- else
- {
- $userPrincipal.ChangePassword($currentPassword, $preferredPassword)
- $currentPassword=$preferredPassword
- }
- $validate=$principalContext.ValidateCredentials($userName,$currentPassword)
- Write-Host "`nValidating password change"
- if($validate)
- {
- Return "Password validation succeeded"
- }
- Else
- {
- $passwordList | Out-File (((Get-ChildItem).DirectoryName | select -First 1)+"\passwordList.txt")
- throw $Error[0].Exception.Message + "Please check the password list file in" + (((Get-ChildItem).DirectoryName | select -First 1)+"\passwordList.txt")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement