1

I'm currently stuck getting a PowerShell error when trying to run a script I have written (Read stolen from the internet)

What I am trying to achieve is to search for a specific users e-mail address within one of the multiple O365 distribution Groups and then remove that user from the group if the group is one that meets the criteria.

The groups are all prefixed with the text "EX_SIG" and I am able to identify the one group the user is a member of but I'm struggling to then translate this into remove the user from the identified group.

I am a complete PowerShell newbie so any help would be appreciated.

Code:

$UAC_email = "sarah.connor@skynet.com"

$UAC_EX_GROUP = Get-DistributionGroup -identity "EX_SIG*" | where { (Get-DistributionGroupMember $_.name | foreach {$_.PrimarySmtpAddress}) -contains "$UAC_email"} | FT name -HideTableHeaders

Remove-DistributionGroupMember -Identity $UAC_EX_GROUP -Member "$UAC_email"

Error:

Cannot bind argument to parameter 'Identity' because it is null.

jkdev
  • 11,360
  • 15
  • 54
  • 77
Ian Stoker
  • 11
  • 1
  • So you have a user that that if they're a member of any groups that match EX_SIG* for the name then you want to remove them from the group? – SteamerJ Sep 23 '19 at 18:44

2 Answers2

2

The FT (Format-Table) cmdlet is likely causing most of your problems. You shouldn't try to use output from formatting cmdlets except with out-* commands.

Format- cmdlets output "typesetting" objects which the host uses to format the display, not usable objects for the pipeline.

$UAC_email = "sarah.connor@skynet.com"

$UAC_EX_GROUP = Get-DistributionGroup -identity "EX_SIG*" | where { (Get-DistributionGroupMember $.name | foreach {$.PrimarySmtpAddress}) -contains "$UAC_email"}

Remove-DistributionGroupMember -Identity $UAC_EX_GROUP -Member "$UAC_email"
Mike Shepard
  • 17,466
  • 6
  • 51
  • 69
1

Try this as it is a lot cleaner than the code you posted but should accomplish your goal.

$UAC_email = "sarah.connor@skynet.com"  

#Get list of distribution groups where identity matches "EX_SIG*" and the email address your looking for is in the list of the group members's primary smtp addresses
$UAC_EX_GROUPS = (Get-DistributionGroup -Identity "EX_SIG*") | Where-Object{(Get-DistributionGroupMember -Identity $_.Name).PrimarySmtpAddress -contains $UAC_email}

#Iterate over returned groups and remove the member from the group. I put a WHATIF in there so you can verify the output before just running it. You can also pipe this directly before the closing '}' in the previous command but it's less readable that way
$UAC_EX_GROUPS | Remove-DistributionGroupMember -Identity $_.Name -Member $UAC_email -WhatIf
SteamerJ
  • 111
  • 4