Powershell Script For Report of DL Script

Hi All,

I am trying to run a powershell script which i am going to paste below which basically runs for office365 and fetches dl owners and members but somehow i receive an error as below:

Script-
#Change

Import necessary modules

Import-Module ImportExcel
Import-Module ExchangeOnlineManagement

Set Execution Policy

#Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force

Connect to Exchange Online

Connect-ExchangeOnline -UserPrincipalName “” -ShowProgress $true -ExchangeEnvironmentName O365Default

<#$UPN = “vrushabh.chitalia@agreem.in”
$Password = ConvertTo-SecureString “DataScientist@96” -AsPlainText -Force

Create a credential object

$UserCredential = New-Object System.Management.Automation.PSCredential($UPN, $Password)

Connect to Exchange Online

Connect-ExchangeOnline -Credential $UserCredential#>

Get all distribution lists

$distributionLists = Get-DistributionGroup -ResultSize Unlimited

Create a hashtable to store DLs, owners, and members

$dlDetails = @{}

Iterate through each distribution list

foreach ($dl in $distributionLists) {
Write-Debug “$dl”
# Get members of the distribution list
$members = Get-DistributionGroupMember -Identity $dl.Identity -ResultSize Unlimited | Select-Object -ExpandProperty PrimarySmtpAddress
Write-Debug “$members”
# Get owners of the distribution list
$ownerIdentities = Get-DistributionGroup -Identity $dl.Identity | Select-Object -ExpandProperty ManagedBy
Write-Debug “$ownerIdentities”
# Initialize an array to store owner email addresses
$owners = @()

foreach ($owner in $ownerIdentities) {
    try {
        Write-Debug "$owner"
        $ownerEmail = (Get-Recipient $owner).PrimarySmtpAddress
        $owners += $ownerEmail
    } catch {
        Write-Host "Failed to get email for owner: $owner"
    }
}

# Add the DL, its owners, and its members to the hashtable
$dlDetails[$dl.DisplayName] = @{
    Owners = $owners
    Members = $members
}

}

Prepare data for Excel

$headers = $dlDetails.Keys
$maxRows = ($dlDetails.Values | ForEach-Object { $.Owners.Count + $.Members.Count }) | Measure-Object -Maximum | Select-Object -ExpandProperty Maximum

Create an array to hold the data for Excel

$excelData = @()

<# Add headers as the first row
$headerRow = [PSCustomObject]@{}
foreach ($header in $headers) {
$headerRow | Add-Member -MemberType NoteProperty -Name $header -Value “”
}
$excelData += $headerRow#>

Add owners and members under each header

for ($i = 0; $i -lt $maxRows; $i++) {
$row = [PSCustomObject]@{}
foreach ($header in $headers) {
#$owners = $dlDetails[$header].Owners
$members = $dlDetails[$header].Members
$value = if ($i -lt ($members.Count)) { $members[$i] } else { “” }
#$value = if ($i -lt $owners.Count) { $owners[$i] } elseif ($i -lt ($owners.Count + $members.Count)) { $members[$i - $owners.Count] } else { “” }
$row | Add-Member -MemberType NoteProperty -Name $header -Value $value
}
$excelData += $row
}

Get the current date in yyyy-MM-dd format

$dateSuffix = (Get-Date).ToString(“dd-MM-yyyy hh-mm tt”)

Export to Excel

$excelData | Export-Excel -Path “C:\Users\Admin\Desktop\DLs_and_Members_$dateSuffix.xlsx” -WorksheetName “DistributionLists” -AutoSize

Function to convert list to HTML table

function ConvertTo-HTMLTable {
param (
[string]$dlName,
[string]$members
)
$html = “

$dlName


foreach ($member in $members) {
$html += “”
}
$html += “
Members
$member

return $html
}

Disconnect from Exchange Online

Disconnect-ExchangeOnline -Confirm:$false

Write-Host “n~~ Script prepared by Agreem Team ~~n” -ForegroundColor Green

Error:
Write-ErrorMessage : Ex6F9304|Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException|The operation couldn’t be performed because object ‘Organization Management’ couldn’t be found on ‘BMXPR01A10DC003.INDPR01A010.PROD.OUTLOOK.COM’. At C:\Users\Administrator\AppData\Local\Temp\3\tmpEXO_n4z4p1ao.52k\tmpEXO_n4z4p1ao.52k.psm1:1207 char:13 + Write-ErrorMessage $ErrorObject + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:slight_smile: [Get-Recipient], ManagementObjectNotFoundException + FullyQualifiedErrorId : [Server=PN0P287MB0550,RequestId=dd4c7e61-2f81-e149-84ab-cb013d7d9399,TimeStamp=Wed, 27 Nov 2024 06:32:19 GMT],Write-ErrorMessage

Hello and welcome to the forum. Please make sure to format any code or console output as “formatted text”. You can edit your post and use the preformatted texr button, sometimes behind the gear icon.

Also, your password is compromised.

<#$UPN = “vrushabh.chitalia@agreem.in”
$Password = ConvertTo-SecureString “DataScientist@96” -AsPlainText -Force

The error occurs because Get-Recipient cannot find the “Organization Management” object, likely due to non-recipient owners in the distribution list.

Solutions:

  1. Use Get-User instead of Get-Recipient to ensure valid email addresses for owners:

powershell

Copy code

$ownerEmail = (Get-User $owner).PrimarySmtpAddress
  1. Handle errors gracefully by skipping invalid owners:

powershell

Copy code

try {
    $ownerEmail = (Get-User $owner).PrimarySmtpAddress
    $owners += $ownerEmail
} catch {
    Write-Host "Failed to get email for owner: $owner"
}

This should resolve the issue by handling non-recipient owners properly.

It was just that owner is not present in dl’s weird error was throwing up in powershell!

you still haven’t removed your account password from your first post.

I don’t get option to edit the post as it is not my password anymore!

I can’t edit my reply either. Glad you changed it! :grinning: