Hello, I have a problem with a script in poweshell, I am investigating about a script to delete multiple users in different distribution groups in office 365, I have the user but I do not have the groups, google search and find this script:

$host.Runspace.ThreadOptions = "ReuseThread"
Conexión a Office 365
$msolcred = get-credential
connect-msolservice -credential $msolcred

$Users = Import-Csv D:\Documentos\PowerShell\EliminarMiembrosGrupos.csv |%{$_.email}

# looping through Each user in $Users Loop imported from CSV File
foreach($ThisUser in $Users)
{
"$ThisUser - Procesando....`n"

#Get Mail Enabled Distribution Group Info
$DistributionGroup = Get-DistributionGroup -ResultSize Unlimited | where { (Get-DistributionGroupMember $_ | foreach {$_.PrimarySmtpAddress}) -contains $ThisUser}

#Loop Through Distribution Groups in which the User is MemberOf
foreach($ThisDG in $DistributionGroup)
{
"$ThisDG - Procesando...`n"
"Removiendo usuario - $ThisUser del grupo - $ThisDG....`n"
#Remove Group membership for the user
Remove-DistributionGroupMember $ThisDG -Member $ThisUser
}
}

Write-Host "Proceso finalizado con éxito"  -foregroundcolor Green

But when I run it gives me the following error

Cannot process argument transformation on parameter 'Identity'. Cannot convert value "GROUP_NAME" to type 
"Microsoft.Exchange.Configuration.Tasks.DistributionGroupMemberIdParameter". Error: "Cannot convert hashtable to an object of the following type: 
Microsoft.Exchange.Configuration.Tasks.DistributionGroupMemberIdParameter. Hashtable-to-Object conversion is not supported in restricted language mode or a Data 
section."
    + CategoryInfo          : InvalidData: (:) [Get-DistributionGroupMember], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-DistributionGroupMember
    + PSComputerName        : outlook.office365.com

Could they help me and guide me in what I am doing wrong? I thank you very much.

2 Spice ups

Welcome!

Please tag PowerShell scripts as powershell when you post code. Please and thank you

codebutton_small.png

Maybe try like so, not sure, I have nothing to test against around

$host.Runspace.ThreadOptions = "ReuseThread" # ??

$msolcred = Get-Credential
connect-msolservice -credential $msolcred

$Users = Import-Csv D:\Documentos\PowerShell\EliminarMiembrosGrupos.csv

# looping through Each user in $Users Loop imported from CSV File
foreach($ThisUser in $Users.email){
    Write-Output "$ThisUser - Procesando....`n"

    #Get Mail Enabled Distribution Group Info
    $DistributionGroup = Get-DistributionGroup -ResultSize Unlimited | 
                         where {(Get-DistributionGroupMember).PrimarySmtpAddress -contains $ThisUser}

    #Loop Through Distribution Groups in which the User is MemberOf
    foreach($ThisDG in $DistributionGroup){
        Write-Output "$ThisDG - Procesando...`n"
        Write-Output "Removiendo usuario - $ThisUser del grupo - $ThisDG....`n"
        #Remove Group membership for the user
        Remove-DistributionGroupMember $ThisDG -Member $ThisUser
    }
}

Write-Host "Proceso finalizado con éxito"  -foregroundcolor Green

Hello, first of all thanks for your answer, when executing the code you recommend, I mark the following error.

PS C:\Users\Nestor> D:\Documentos\PowerShell\EliminarMiembrosGrupos.ps1
cmdlet Get-Credential en la posición 1 de la canalización de comandos
Proporcione valores para los parámetros siguientes:
email@mail.domain.mx - Procesando....

Creating a new session for implicit remote communication of the "Get-DistributionGroup" command ...
Cmdlet Get-DistributionGroupMember at command pipeline position 1
Supply values for the following parameters:
The command prompt for "Identity" can not be displayed because the "Microsoft.Exchange.Configuration.Tasks.DistributionGroupMemberIdParameter" type can not be loaded.
     + CategoryInfo: ResourceUnavailable: (:) [], PromptingException
     + FullyQualifiedErrorId: System.Management.Automation.Host.PromptingException
     + PSComputerName: outlook.office365.com

Odd… What does your CSV look like? Can you please post a sanitized sample?

email
user01@mail.domain.com
user02@mail.domain.com
...

This worked for me… kind of.

$msolcred = Get-Credential
connect-msolservice -credential $msolcred

$Users = Import-Csv C:\test.csv

# looping through Each user in $Users Loop imported from CSV File
foreach($ThisUser in $Users.email){
    Write-Verbose "$ThisUser - Procesando....`n" -Verbose

    #Get Mail Enabled Distribution Group Info
    $DistributionGroup = Get-DistributionGroup -ResultSize Unlimited | 
                         where {(Get-DistributionGroupMember $_.PrimarySmtpAddress) -contains $ThisUser}

    #Loop Through Distribution Groups in which the User is MemberOf
    foreach($ThisDG in $DistributionGroup){
        Write-Verbose "$ThisDG - Procesando...`n" -Verbose
        Write-Verbose "Removiendo usuario - $ThisUser del grupo - $ThisDG....`n" -Verbose
        #Remove Group membership for the user
        Remove-DistributionGroupMember $ThisDG -Member $ThisUser -WhatIf
    }
}

Write-Host "Proceso finalizado con éxito"  -foregroundcolor Green

With your code I do not see any error just this warning

WARNING: By default, only the first 1000 items are returned. Use the ResultSize parameter to specify the number of items returned. To return all items, 
specify "-ResultSize Unlimited". Note that depending on the actual number of items, returning all items can 
take a long time and consume a lot of memory. In addition, it is not recommended to store the results in a variable. Instead, stream the results 
to another task or script to make batch changes.

It finishes the process, however it does not remove the user group, they are still inside and in the log of the code I do not appear the messages of “Removing user from the group”

You have to see how you create the distribution groups?