Remove-AdObject with Import-CSV 错误

Remove-AdObject with Import-CSV error

我对 Powershell 还很陌生,如果这很简单,我深表歉意。我曾尝试使用来自用户 和 运行 的示例脚本,导致我认为 AdObject 应该绕过的错误。我的脚本

Import-Module ActiveDirectory

$list = Import-CSV C:\scripts\deletebulkusers.csv

forEach ($item in $list) {
    $samAccountName = $item.samAccountName

    #Get DistinguishedName from SamAccountName
    $DN = Get-ADuser -Identity $Samaccountname -Properties DistinguishedName |
        Select-Object -ExpandProperty DistinguishedName

    #Remove object using DN
    Remove-ADObject -Identity $DN
}

我在下面发布了我的错误:

Remove-ADObject : The directory service can perform the requested operation only on a leaf object
At line:13 char:5
+     Remove-ADObject -Identity $DN -confirm:$false
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (CN=<user>,DC=com:ADObject) [Remove-ADObject], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8213,Microsoft.ActiveDirectory.Management.Commands.RemoveADObject

该错误表明您要删除的对象是一个容器。我怀疑您可能正在向 cmdlet 证明您要删除的对象的容器而不是对象本身。

我认为您可以使用管道简化情况:

Get-ADuser -Identity $Samaccountname | Remove-ADObject -WhatIf

如果 -WhatIf 参数符合您的预期,请删除它。

很高兴我能提供帮助 :) 我以前遇到过这种情况,特别是如果用户的 phone 上有 Outlook,它会将它们变成一个容器。如果您打开 Active Directory 用户和计算机,select "View",并选中 "View Users, Contacts, Groups and Computers as containers" 导航到该对象的选项,您将看到其中有项目。

-recurse 参数与 Remove-ADObject 一起使用是为我修复它的方法。

这是我的结束脚本的样子。 and 的两个答案都解决了我的问题。谢谢大家!!

 Import-Module ActiveDirectory

$list = Import-CSV C:\scripts\deletebulkusers.csv

forEach ($item in $list) {
    $samAccountName = $item.samAccountName

    $DN = Get-ADuser -Identity $Samaccountname | Remove-ADObject -Recursive 
}