我有一个脚本可以通过以下步骤禁用AD中的用户:
现在,当我第一次尝试时,它不起作用。我必须运行它几次,比如2 3和4次才能工作。
当我一步一步地运行它时,它也可以从第一次开始正常运行
这是脚本:
$username = Read-Host -Prompt 'Enter Username'
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Import-Module ActiveDirectory
$user = Get-ADUser -Filter {(SamAccountName -eq $username)} -Properties MemberOf
#set "domain users" group as primary group
$group = get-adgroup "Domain Users" -properties @("primaryGroupToken")
get-aduser $username | set-aduser -replace @{primaryGroupID=$group.primaryGroupToken}
#disable users in AD
Get-ADUser -Filter {(SamAccountName -eq $username)} | Disable-ADAccount -ErrorAction SilentlyContinue
#move to disabled OU
Get-ADUser -Filter {(SamAccountName -eq $username)} | Move-ADObject –TargetPath “OU=Users,OU=Disabled Objects,DC=xxxxxxx,DC=xxx,DC=XXX”
#clear Manager from AD
Get-ADUser -Filter {(SamAccountName -eq $username)} | Set-ADUser -Clear manager
#-------------------------
#remove all groups except 'domain users'
Get-ADPrincipalGroupMembership -Identity $username | % {Remove-ADPrincipalGroupMembership -Identity $username -MemberOf $_ -Confirm:$false -ErrorAction SilentlyContinue}
#code can be removed.
#$group = $user | Select-Object -ExpandProperty MemberOf
#Remove-ADGroupMember -Identity $group -Members $user.SamAccountName -Confirm:$false -ErrorAction SilentlyContinue
#-------------------------
#Add disabled_mailboxes to the user
Add-ADGroupMember -Identity 'disabled_mailboxes' -Member $User.SamAccountName -ErrorAction SilentlyContinue
#-------------------------
#Hide account from exchande list
Set-Mailbox -identity $user.SamAccountName -HiddenFromAddressListsEnabled $true -ErrorAction SilentlyContinue
Windows 2012R2,Exchange 2010
任何人都可以帮忙吗???
由于
米娜
答案 0 :(得分:0)
请勿在连续行中重复使用Get-ADUser
。只需使用刚填充了值的现有$user
变量即可。很可能您遇到Get-ADUser
在运行Move-ADObject
之后立即返回DN的旧缓存值的问题(这会更改用户的DN),并且由于所有查询都使用DN来定位用户,因此得到错误。第二次运行的目标用户已经在目标OU中,因此不会出现错误。