Lock-ADUser.ps1

function Lock-ADUser
{
  <#
    .SYNOPSIS
    Locks the account of the specified user.
    .DESCRIPTION
    Attempts to run a process against the specified server with invalid credentials for the target user. This is done until the account is locked in Active Directory.
    .EXAMPLE
    Lock-ADUser -target baduser1 -server dc01
    .EXAMPLE
    Lock-ADUser baduser1 dc01
    .EXAMPLE
    Lock-ADUser baduser1
    This will lock baduser1 and attempt running a process of the currently logged in user's $env:LOGONSERVER
  #>

  [CmdletBinding()]
  param
  (
    [Parameter(Mandatory=$true, Position=0)]
    [Object]
    $target = (Read-Host 'Who needs locked out?'),
    
    [Parameter(Mandatory=$false, Position=1)]
    [Object]
    $Server = $env:logonserver.Replace('\','') #(Read-Host 'Enter the name of a valid computer to attempt logging in against.')
  )
  
  #Requires -Version 3.0
  #Requires -Modules ActiveDirectory
  
  
  
  
  try {
    $user = Get-ADUser $target -Properties LockedOut -ErrorAction Stop
    Write-Verbose "User $target has been located."
  }
  catch {
    Write-Error "Error getting user account for $target"
    throw
  }
  
  if ($user.Enabled -eq $false) {
    Write-Error "User $($user.samaccountname) is not enabled. Script will not process properly due to this. Exiting."
    throw
  }
  
  Try {
    $badPassword = ConvertTo-SecureString 'NotMyPassword' -AsPlainText -Force -ErrorAction Stop
  }
  Catch {
    Write-Error "Error generating a bad secure password string."
    throw
  }
  
  
  if (!$user.LockedOut) {
    Write-Verbose "User $target is not currently locked out. Doing work."
    
    while ($user.LockedOut -ne $true) {
      Invoke-Command -ComputerName $Server {Get-Process} -Credential (New-Object System.Management.Automation.PSCredential ($($user.UserPrincipalName), $badPassword)) -ErrorAction SilentlyContinue | Out-Null 
      Start-Sleep -Milliseconds 250
      $user = Get-ADUser $target -Properties LockedOut
    } 
  }
   
  if ($user.LockedOut) {
    Write-Output "User $($user.SamAccountName) is now locked."
  }
}