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

Hi,

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.

Thanks
adamtraskAsked:
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


Will.
0
 
oBdACommented:
# 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
	}
	Exit
}
"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 {
	Write-Host
	$_.Exception.Message | Write-Host -Foregroundcolor Red
	$_.InvocationInfo.PositionMessage | Write-Host -Foregroundcolor Red
}

Open in new window

0
 
David Johnson, CD, MVPOwnerCommented:
no points: oBda -- like your solution!
0
 
adamtraskAuthor Commented:
Thank you very much.... oBda -- I need to spend some time studying your solution. Thank you.
0
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.