Add-DistributionGroupMember with variable

Is it possible to add members to a DistributionGroup using a variable. Importing a CSV file works but can be time consuming.


$users = Get-Mailbox -Filter {RecipientTypeDetails -eq "UserMailbox"}

Adding the members, if I try to pipe foreach after the Add-DistributionGroupMember cmdlet the -Member parameter is missing.

PS C:\Windows\System32\WindowsPowerShell\v1.0> $users | foreach {Add-DistributionGroupMember -Identity EveryoneGroup -Member $_.users}
Cannot validate argument on parameter 'Member'. The argument is null. Supply a non-null argument and try the command again.
    + CategoryInfo          : InvalidData: (:) [Add-DistributionGroupMember], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Add-DistributionGroupMember
    + PSComputerName        :

I’m probably doing something very stupid here…

I suspect you’re just accessing the wrong property name inside your ForEach-Object block; “Users” seems like an unlikely name for a property on the output from Get-Mailbox.

Based one what I can see of the documentation for these cmdlets on TechNet, I think $_.UserPrincipalName should work. (I don’t have an Exchange environment up at the moment where I can test that.)

Sorry, total lack of comprehension on my part…Your right, your suggestion worked! Thank you

PS C:\Windows\System32\WindowsPowerShell\v1.0> $users | foreach {Add-DistributionGroupMember -Identity EveryoneGroup -Member $_.UserPrincipalName}