Reputation: 340
Running this code in a script (that grabs details from a form) to get a list of users groups and remove from all except group named "Group1" and "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
}
}
The script works and you can see that the groups have been removed, however logs show a "Cannot bind argument to parameter 'Name' because it is null." error for each group that matches that criteria":
[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.
I know it's likely something really simple in the logic of the foreach
loop I'm missing.
Upvotes: 1
Views: 2366
Reputation: 6864
This line seems like your problem: $group = $groups.name
It is surprising to see you accessing the array ($groups
) inside a foreach loop iterating across those elements. Did you mean $group = $group.name
?
Upvotes: 4