Convert Object to String

I’m working with Exchange and getting hung up on the fact that if I assign a variable to a list that is either read from the pipeline, or imported with import-csv, the list is one of objects, not strings, and when I wish to then loop through the list with an operation, the operation is expecting a string, not an object.

My use-case here is that I have a list of UserPrincipalNames (i.e. email accounts), that I wish to remove from a list of distribution groups.

So, for example:

$abcdepeeps = Get-Content abcdepeeps.txt 

$abcdegroups = Get-DistributionGroup -domain abcde.com 

foreach ($peep in $abcdepeeps) {
    foreach($group in $abcdegroups) { 
            remove-distributiongroupmember -identity $group -member $peep 
}
}

This brings up an error that says the distribution group list are objects, not strings.

Cannot process argument transformation on parameter ‘Identity’. Cannot convert the
“ABCDE.Logistics” value of type “Deserialized.Microsoft.PowerShell.Commands.MatchInfo” to
type “Microsoft.Exchange.Configuration.Tasks.DistributionGroupIdParameter”.

  • CategoryInfo : InvalidData: (:slight_smile: [Remove-DistributionGroupMember], ParameterBind
    in…mationException
  • FullyQualifiedErrorId : ParameterArgumentTransformationError,Remove-DistributionGroupMem
    ber
  • PSComputerName : outlook.office365.com

My workaround is to write out the object to a text file and then reimport, but that is such a pain…I keep thinking there should be a function that would do the conversion?

 

I don’t have an infrastructure to test at moment but I think you have at least 2 options. You could either specify the needed property already in your loop definition like this:

foreach ($peep in $abcdepeeps) {
foreach ($group in $abcdegroups.sAMAccountName) {
remove-distributiongroupmember -identity $group -member $peep
}
}

Or you specify the needed property inside the loop:
foreach ($peep in $abcdepeeps) {
foreach ($group in $abcdegroups) {
remove-distributiongroupmember -identity $group.sAMAccountName -member $peep
}
}

If I am not wrong, you are doing implicit remoting, hence you cannot use the object as is(they are deserialized). So @Olaf-Soyk 's solution is the best here.

Everything in PS is an object by design / default.
So, unless what is in here: abcdepeeps.txt, is a single column list, then you have to specify the property to use.
Example:

You are also passing in a object collection with this: Get-DistributionGroup -domain abcde.com, so this too, needs it’s property to be specified.

Example

foreach ($peep in $abcdepeeps) {
foreach($group in $abcdegroups) {
remove-distributiongroupmember -identity $group.Name -member $peep.Name
}
}

Thanks all…I’ll try these!