Enable and Disable Active Directory Account with PowerShell

Recently I had to create a generic active directory account for testing software.  I want the account disabled when I am not using it, so I created this PowerShell script to enable and disable the account.

 

Param(
# Account
[Parameter(Mandatory=$true,HelpMessage='Active Directory Login ID?',Position=0)]
$Account,
# Enable or disable
[Parameter(Mandatory=$true,HelpMessage='Enable Account? (Y/N)',Position=1)]
$Enable?
)

$defaultAcct = 'myDefaultAcct'
$enableAcct = $false

if ($Account -eq $null -or $Account -eq "") {$Account = $defaultAcct}
if ($Enable?.ToUpper() -eq 'Y' -or $Enable?.ToUpper() -eq "YES") {$enableAcct = $true}
Elseif ($Enable?.ToUpper()-eq 'N' -or $Enable?.ToUpper() -eq 'NO') {$enableAcct = $false}
Else {"You must enter Y, Yes, N, or No. Run the command again and use a valid input."
exit}
Try {
Get-ADUser -Identity $Account | Select-Object @{name="Status"; expression={"Before Change"}},@{name="Account"; expression={$_.SamAccountName}},@{name="Enabled"; expression={$_.Enabled}} | Format-List
} Catch {
"Error: $_ "
exit
}

Set-ADUser -Identity $Account -Enabled $enableAcct

Get-ADUser -Identity $Account | Select-Object @{name="Status"; expression={"After Change"}},@{name="Account"; expression={$_.SamAccountName}},@{name="Enabled"; expression={$_.Enabled}} | Format-List

Comments are closed.