在 AD 中禁用用户的脚本

script for disable user in AD

我正在尝试编写一个脚本来禁用用户,当我 运行 这个脚本它说用户被禁用但是当我检查用户没有被禁用时。有人可以帮我解决这个问题谢谢。我是 PowerShell 新手。

Import-Module ActiveDirectory

$username = Read-Host -Prompt 'Enter the user name.  '
$user = "$username"

{
    Disable-ADAccount -Identity $user
    write-host "user $($user) has been disabled"
}

我已经在我的环境中测试过

正如@Mathias R. Jessen 所建议的那样,花括号 { } 内的代码没有按预期执行代码

解决方法是删除大括号 { }

最终脚本如下:

Import-Module ActiveDirectory

$username = Read-Host -Prompt 'Enter the user name.  '
$user = "$username"
Disable-ADAccount -Identity $user
write-host "user $($user) has been disabled"

除了从 AD 中禁用您的用户外,您可能还想做更多的事情,它可能包含需要删除的组,并且可能需要在禁用后将用户移至其他 OU。我刚才创建了这样一个脚本并且它有效。希望它对某人有所帮助:)

#Collect user's details
$script:existinguser = Read-Host -Prompt "Enter the username for the user you wish to disable and modify (ex: jsnow)" 


#Checking if the user exists
try {
Get-ADUser -Identity $script:existinguser
$UserExists = $true
Write-Host "User exists, proceeding to disable the account." -ForegroundColor Green
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityResolutionException] {
"Fatal error!User does not exist."
$UserExists = $false
exit
}
#Disabling the account
Disable-ADAccount -Identity $script:existinguser
Write-Output "The account for the user $script:existinguser has been succesfully disabled." 
Write-Output "Proceeding to the next step" 

#Removing groups from user
Try{
$user=Get-ADUser -Identity $script:existinguser |select -exp samaccountname - 
ErrorAction stop
if($user){
$ADgroups= Get-ADPrincipalGroupMembership -Identity  $user | where {$_.Name -ne 
“Domain Users”}
write-host "removing user from `n` $($adgroups.name)" -ForegroundColor green
Remove-ADPrincipalGroupMembership -Identity  $user -MemberOf 
$ADgroups.samaccountname -Confirm:$false 
}
}
Catch{ Write-Warning $_.exception.message}

#Moving the user to Past employees
Get-ADUser $script:existinguser| Move-ADObject -TargetPath 'Ou=Past Employees, 
DC=domain, Dc=local'
Write-Output "The user has been moved to the OU Past Employees"

#Filling in the description
$nextmonth  = ((Get-Date).AddMonths(1))
Set-ADUser $script:existinguser -Description "To be archived $nextmonth"