Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Add-Type -AssemblyName Microsoft.VisualBasic
- # Make buttons\icons variables for easier reading.
- $okButton = [System.Windows.Forms.MessageBoxButtons]::OK
- $errorIcon = [System.Windows.Forms.MessageBoxIcon]::Error
- $infoIcon = [System.Windows.Forms.MessageBoxIcon]::Information
- # Ask for a user name
- $username = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a username", "Username")
- # I like to use the PDC for this stuff, plus it always helps to make sure you're talking to the same
- # dc through each command against AD.
- try {
- $pdc = Get-ADDomainController -Discover -Service PrimaryDC -ErroAction STOP | Select-Object -ExpandProperty hostname
- Write-Verbose -Message ('Using PDC: {0}' -f $pdc)
- }
- catch {
- $errorMessage = 'Unable to find PDC: {0}' -f $_.exception.message
- [System.Windows.Forms.MessageBox]::Show($errorMessage,"$username Unlock Error",$okButton,$errorIcon)
- }
- # word dictionary (ideally you might store this in a file somewhere instead of hard coding)
- $words = @('cat','dog','fish','flower','rabbit','horse')
- # pick a random word
- $word = $words | Get-Random
- # Get a random number with 4 digits
- $number = '{0:D4}' -f (Get-Random -Maximum 9999)
- # Build your password string
- $password = "$word$number"
- Write-Verbose -Message ('Picked password: {0}' -f $password)
- # Create a basic splat to pass in some standard parameters...again easier reading
- $cmdSplat = @{
- Identity = $username
- Server = $pdc
- ErrorAction = 'STOP'
- }
- # Try to unlock the account, and then set the password and for to change at next logon. If the all of the AD cmdlets work
- # then return the confirmation success, otherwise fail. With the try-catch...it will only move on to the next command if
- # the preceding one was a success. If one fails then it immediately goes to the catch block.
- try {
- Unlock-ADAccount @cmdSplat
- Set-ADAccountPassword @cmdSplat -NewPassword (ConvertTo-SecureString -AsPlainText "$password" -Force)
- Set-ADUser @cmdSplat -ChangePasswordAtLogon $true -PasswordNeverExpires $false
- $confirmation = "User account $username has been unlocked, and password has been set to $password"
- [System.Windows.Forms.MessageBox]::Show($confirmation,"$username Unlock Success",$okButton,$infoIcon)
- }
- catch {
- $errorMessage = 'Failed to set password for {0} on {1}: {2}' -f $username,$dc,$_.exception.message
- [System.Windows.Forms.MessageBox]::Show($errorMessage,"$username Unlock Error",$okButton,$errorIcon)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement