Using a power shell batch file to disable a user in Active directory


I need help creating a power shell batch file that would disable a user in Active directory.
Of course the file needs to prompt for the ADUser name and then proceed to disable him/her.

It would be a bonus if the file could also include code to move the newly disabled AD user to a folder called OldUsers.

Who is Participating?
Will SzymkowskiSenior Solution ArchitectCommented:
Use the following command below...
Import-module activedirectory
Set-ADUser -Identity (read-host "enter username") -Enabled $false

Open in new window

# OU path to the disabled users OU (DC component not required)
$DisabledUsersPath = "OU=OldUsers"
$UserSAM = Read-Host "Enter the user logon name to disable"
Try {
	$ADUser = Get-ADUser -Identity $UserSAM
} Catch {
	$_.Exception.Message | Write-Warning
	If ($_.CategoryInfo.Category.ToString() -eq "ObjectNotFound") {
		"Users with names similar to '$($UserSAM)':" | Write-Host
		Get-ADUser -Filter "SamAccountName -like '*$($UserSAM)*'" | Select-Object -Property SamAccountName, DistinguishedName | Format-Table -AutoSize
"Found user in AD: $($ADUser.DistinguishedName)" | Write-Host -Foregroundcolor White
Try {
	"Disabling user ... " | Write-Host -Foregroundcolor White -NoNewline
	If ($ADUser.Enabled) {
		Set-ADUser -Identity $ADUser -Enabled $False
		"OK." | Write-Host -Foregroundcolor Green
	} Else {
		"was already disabled." | Write-Host -Foregroundcolor Green
	$TargetPath = $DisabledUsersPath + $ADUser.DistinguishedName.SubString($ADUser.DistinguishedName.IndexOf(",DC="))
	$UserPath = $ADUser.DistinguishedName.SubString($ADUser.DistinguishedName.IndexOf(",OU=") + 1)
	"Moving user to '$($TargetPath)' ... " | Write-Host -Foregroundcolor White -NoNewline
	If ($TargetPath -ne $UserPath) {
		Move-ADObject -Identity $ADUser -TargetPath $TargetPath
		"OK." | Write-Host -Foregroundcolor Green
	} Else {
		"was already in the OU for disabled users." | Write-Host -Foregroundcolor Green
} Catch {
	$_.Exception.Message | Write-Host -Foregroundcolor Red
	$_.InvocationInfo.PositionMessage | Write-Host -Foregroundcolor Red

Open in new window

David Johnson, CD, MVPOwnerCommented:
no points: oBda -- like your solution!
adamtraskAuthor Commented:
Thank you very much.... oBda -- I need to spend some time studying your solution. Thank you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.