Powershell – Get-DistributionGroup output ManagedBy samaccountname

exchangepowershell

I am trying to export a list of all DL's, and I need to be able to have a column with the samaccountname of the ManagedBy value (first entry if multiple).

Get-DistributionGroup | Select-Object Name, ManagedBy | Export-Csv C:\out.txt

Unsurprisingly, this gives me something like this:

"Name","ManagedBy"
"DL-SOMETHING-SOMETHING","Microsoft.Exchange.Data.Directory.ADMultiValuedProperty`1[Microsoft.Exchange.Data.Directory.ADObjectId]"

If this was not a one-liner, I could loop through the ManagedBy values, use GET-AdUser and extract what I need.

But can I do this in a one-liner, if I only care about the first ManagedBy?

Something like…

Get-DistributionGroup | Select-Object Name, ManagedBy[0].Samaccountname | Export-Csv C:\out.txt

If I could even get the same string as I get when I run this in the console, I could work with that:

Get-DistributionGroup | Select-Object Name, ManagedBy

Output

DL-SOMETHING-SOMETHING, {somedomain.com/Accounts/SomeAccount}

Best Answer

Try below command:

Get-DistributionGroup | Select-object Name,@{label="ManagedBy";expression={[string]($_.managedby | foreach {$_.tostring().split("/")[-1]})}} | Export-Csv

It will display like below: enter image description here