在脚本中运行此代码(从表单中获取详细信息)以获取用户组列表并从除“Group1”和“Group2”组之外的所有组中删除:
#remove any group memberships except Group1 and Group2
$groups = Get-ADPrincipalGroupMembership $Inputsamaccountname.Text | Where-Object -filter {$_.name -ne 'Group1' -And $_.name -ne 'Group2'}
foreach ($group in $groups) {
$group = $groups.Name
$RemovegroupMsg = "Removing " + $inputSamAccountName.Text + " from " + $group
logentryDateTime $removeGroupMsg
Remove-ADPrincipalGroupMembership -Identity $inputSamAccountName.Text -MemberOf $group -Confirm:$false
if ($Error) {
$errorMessage = "Error removing " + $inputSamAccountName.Text + " from " + $group + " " + ($Error[0].ToString()) + " continuing."
logentryDateTime $errorMessage
$Error.Clear()
continue
} elseif (!$Error) {
Write-Output "" >> $outlogfile
logentryDateTime "Successfully removed " + $inputSamAccountName.Text + " from " + $group
}
}
该脚本有效,您可以看到这些组已被删除,但是日志显示“无法将参数绑定到参数'Name',因为它为null。”符合该条件的每个组的错误“:
[2016-10-19 113117-820] : Removing user.test1 from Other-group [2016-10-19 113117-820] : Error removing user.test1 from Other-group Cannot bind argument to parameter 'Name' because it is null. continuing.
我知道在我错过的foreach
循环的逻辑中,这可能是非常简单的。
答案 0 :(得分:4)
这一行看起来像你的问题所在:$group = $groups.name
看到你在foreach循环中访问数组($groups
)并迭代这些元素,这是令人惊讶的。您的意思是$group = $group.name
吗?