Share via


Supressing errors (erroraction silentlycontinue not working)

Question

Monday, December 3, 2012 12:16 PM

Good morning everyone.

I've not long answered my own question on a PowerShell query thanks to the prodding of a few, but have now come up with a need to supress error messages.

I have two text files, one containing a list of ad accounts, another containing a list of ad groups.

The list of groups is static. It contains 172 group names.
The list of ad accounts is variable. This will change from day to day use.

The PowerShell script below searches the list of groups for usernames and removes them if/when found.

It works fine however if the user/s is not a member of the group it outputs an error message. As there are 172 groups there's potential for 172 error messages. Is there anyway to supress them?

$groups = get-content c:\groups.txt
$names = get-content c:\desktop\names.txt
foreach ($aduser in $names) { foreach ($adgroups in $groups) { remove-adgroupmember $adgroups –members $aduser -confirm:$false } } 

Remove-ADGroupMember : The specified account name is not a member of the group
At line:1 char:84

  • foreach ($aduser in $names) { foreach ($adgroups in $groups) { remove-adgroup
    member <<<<  $adgroups -members $aduser -confirm:$false } }
        + CategoryInfo          : NotSpecified: (grouptest2:ADGroup) [Remove-ADGroup
       Member], ADException
        + FullyQualifiedErrorId : The specified account name is not a member of th
       e group,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember

I've tried -erroraction Silentlycontinue but this doesn't appear to work. I've also tried TRAP [The specified name is not a member of the group,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember] { "Error ignored" } but to no avail.

Any advise would be appreciated.

Thanks for your time :)

All replies (3)

Monday, December 3, 2012 12:32 PM ✅Answered | 1 vote

foreach ($aduser in $names) { 
   foreach ($adgroups in $groups) { 
      try{
         remove-adgroupmember $adgroups –members $aduser -confirm:$false 
      }catch{}
   } 
} 

Monday, December 3, 2012 12:26 PM | 1 vote

trap{continue} remove-adgroupmember $adgroups -members $aduser -confirm:$false


Monday, December 3, 2012 1:58 PM

Worked like a charm.

Thanks.