我正在尝试使用PowerShell删除OU中的所有用户,我在下面的SAMAccount名称被卡住了,我希望它删除所有找到的用户。
我在这做错了什么?
$search="OU=Staff,OU=Users,DC=Testing, DC=Local"
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName | Select-Object SamAccountName
$numusers=($deletes.count)
echo "$numusers Users Found"
foreach ($delete in $deletes)
{
echo "Deleting user account $delete . . . "
remove-aduser -identity $delete -confirm:$false
}
这是输出。看似在这里出错 - 无法转换" @ {SamAccountName = bbonhomme}"
找到7个用户
Deleting user account @{SamAccountName=bbonhomme} . . .
Remove-ADUser : Cannot bind parameter 'Identity'. Cannot convert value "@{SamAccountName=bbonhomme}" to type
"Microsoft.ActiveDirectory.Management.ADUser". Error: "Cannot convert the "@{SamAccountName=bbonhomme}" value of type
"Selected.Microsoft.ActiveDirectory.Management.ADUser" to type "Microsoft.ActiveDirectory.Management.ADUser"."
At C:\Users\Administrator\Desktop\import\getadusers.ps1:11 char:29
+ remove-aduser -identity @delete -confirm:$false
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Remove-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.RemoveADUser
答案 0 :(得分:4)
替换
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName | Select-Object SamAccountName
通过
$deletes= Get-ADUser -SearchBase $search -filter * -properties SamAccountName
添加Select-Object意味着将ADUser“object”转换为“Psobject”。结果是后续命令remove-ADuser无法识别此类对象。
也替换:
remove-aduser -identity $deletes -confirm:$false
通过
remove-aduser -identity $delete.SamAccountName -confirm:$false
通过$ delete更改$ deletes(您无法在-Identity参数中指定集合)