title: Powershell Script For Removing Users from Distribution list
body: <p>Since I was notified I could not ask to write code, revising the posting. 
  I have this code. It does run but does not pull any data into the cvs file or actually remove users from the DL. Not sure why its not working. This is run on an on-premise exchange server 2010 with exchange management console. Im pretty sure this is where I am messed up, but not sure how to correct it. where-object {($_.identity -eq "o365.test3") } </p>
  
  <pre><code> Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 
  #path to output file
  $OutFile = 'C:\Scripts\Logs\' 
  $OutFile_LOG = $OutFile+'DL_removeusers_'+$(get-date).ToString('yyyyMMdd')+'.csv'
  
  $totalObj = @()
  #get all distribution groups
  $temp = Get-DistributionGroup -ResultSize Unlimited | 
  ForEach-Object { 
    #get certain user from Distribution Lists
    [array]$mem = Get-DistributionGroupMember -id $_ -ResultSize Unlimited | where-object {($_.identity -eq "o365.test3") } 
    for ($i = 0; $i -lt $mem.Count; $i++) { 
      $member = $mem[$i].name 
  
      #remove user from distribution group
      Remove-DistributionGroupMember -Identity $_ -Member $mem[$i].DistinguishedName -BypassSecurityGroupManagerCheck -confirm:$false     
      $obj = New-Object System.Object 
      $obj | Add-Member -MemberType NoteProperty -Value $_.Name -Name 'Distribution Group' -Force 
      $obj | Add-Member -MemberType NoteProperty -Value $member -Name 'Members' -Force 
      $obj | Add-Member -MemberType NoteProperty -Value $mem[$i].SamAccountName -Name 'SamAccountName' -Force 
      $obj | Add-Member -MemberType NoteProperty -Value $mem[$i].identity -Name 'OU' -Force -PassThru 
      $totalObj += $obj 
    } 
  }
  
  #create output file
  $totalObj | Export-Csv $OutFile_LOG
  Read-Host -Prompt “Press Enter to exit” 
  </code></pre>