Powershell Script throwing error

Hi Community when i am running the below script i am getting error :===================== SETTINGS =====================
param([string]$TargetOwner = “user@domain.com”)
$ErrorActionPreference = ‘Stop’$ProgressPreference = ‘SilentlyContinue’
$SendOwnerEmails = $true$SendITEmail     = $true
$DateSuffixTight = (Get-Date).ToString(‘dd-MM-yyyy_hh-mm_tt’)$DateSuffixDL    = (Get-Date).ToString(‘dd-MM-yyyy hh-mm tt’).Replace(‘:’,‘-’)
$BaseOwner_Members  = ‘C:\psscr\UnifiedGroups’$BaseUnified_IT     = ‘C:\psscr\UnifiedGroups\ReportforIT’
$allFolders = @($BaseOwner_Members,$BaseUnified_IT)foreach($f in $allFolders){ if(-not (Test-Path $f)){ New-Item -ItemType Directory -Path $f -Force | Out-Null } }
$ITRecipients = @(‘test@test.in’)
========== MODULES & AUTH ========
Import-Module ImportExcelImport-Module ExchangeOnlineManagementConnect-ExchangeOnlineConnect-AzureAD
function New-OwnerSheetData {param([string]$SheetName,[string]$Members)foreach($m in $Members){ [PSCustomObject]@{ $SheetName = $m } }}
function Build-ColumnMatrix {param([hashtable]$MapDisplayToMembers)$headers = $MapDisplayToMembers.Keys$maxRows = ($MapDisplayToMembers.Values | ForEach-Object { $_.Count }) | Measure-Object -Maximum | Select-Object -ExpandProperty Maximum$rows = @()for($i=0;$i -lt $maxRows;$i++){$row = [PSCustomObject]@{}foreach($h in $headers){$members = $MapDisplayToMembers[$h]$value = if($members.Count -eq 1 -and $i -eq 0){ $members } elseif($i -lt $members.Count){ $members[$i] } else { ‘’ }$row | Add-Member -MemberType NoteProperty -Name $h -Value $value -Force}$rows += $row}return $rows}
======== DATA COLLECTION ========
$TargetOwner = $TargetOwner.ToLower()   # normalize once$OwnerData = @{}$M365_ITRows = @(); $SG_ITRows = @(); $DL_ITRows = @()
— M365 Groups —
$M365_allGroups = Get-UnifiedGroup -ResultSize Unlimited | Where-Object {$.ResourceProvisioningOptions -contains ‘Team’ -or $.AccessType -in @(‘Private’,‘Public’) -or ($_.ResourceProvisioningOptions.Count -eq 0)}
$M365_MapForIT = @{}foreach($g in $M365_allGroups){$members = Get-UnifiedGroupLinks -Identity $g.Identity -LinkType Members -ResultSize Unlimited | Select-Object -ExpandProperty PrimarySmtpAddress$owners  = Get-UnifiedGroupLinks -Identity $g.Identity -LinkType Owners  -ResultSize Unlimited | Select-Object -ExpandProperty PrimarySmtpAddress$owners  = $owners | ForEach-Object { $_.ToLower() }
if($TargetOwner -and ($owners -notcontains $TargetOwner)){ continue }

$M365_MapForIT["$($g.DisplayName) ($($g.PrimarySmtpAddress))"] = $members
foreach($o in $owners){
    if(-not $OwnerData.ContainsKey($o)){ $OwnerData[$o] = @() }
    $OwnerData[$o] += @{ GroupName = $g.DisplayName; Members = $members }
}
}$M365_ITRows = Build-ColumnMatrix -MapDisplayToMembers $M365_MapForIT
— Security Groups —
$mailEnabledSGs = Get-DistributionGroup -ResultSize Unlimited | Where-Object { $.RecipientTypeDetails -eq ‘MailUniversalSecurityGroup’ }$nonMailSGs = Get-AzureADGroup | Where-Object { $.SecurityEnabled -eq $true -and -not $.MailEnabled -and ($.GroupTypes -notcontains ‘Unified’) -and ($_.GroupTypes -notcontains ‘DynamicMembership’) }
$SG_MapForIT = @{}foreach($sg in $mailEnabledSGs){$members = Get-DistributionGroupMember -Identity $sg.Identity -ResultSize Unlimited | Select-Object -ExpandProperty PrimarySmtpAddress$owners  = (Get-DistributionGroup -Identity $sg.Identity).ManagedBy | ForEach-Object { (Get-Recipient -Identity $_ -ErrorAction SilentlyContinue).PrimarySmtpAddress }$owners  = $owners | Where-Object { $_ } | ForEach-Object { $_.ToLower() }
if($TargetOwner -and ($owners -notcontains $TargetOwner)){ continue }

$SG_MapForIT[$sg.DisplayName] = $members
foreach($o in $owners){
    if(-not $OwnerData.ContainsKey($o)){ $OwnerData[$o] = @() }
    $OwnerData[$o] += @{ GroupName = $sg.DisplayName; Members = $members }
}
}foreach($sg in $nonMailSGs){$members = Get-AzureADGroupMember -ObjectId $sg.ObjectId | Select-Object -ExpandProperty UserPrincipalName$owners  = Get-AzureADGroupOwner -ObjectId $sg.ObjectId | Select-Object -ExpandProperty UserPrincipalName$owners  = $owners | Where-Object { $_ } | ForEach-Object { $_.ToLower() }
if($TargetOwner -and ($owners -notcontains $TargetOwner)){ continue }

$SG_MapForIT[$sg.DisplayName] = $members
foreach($o in $owners){
    if(-not $OwnerData.ContainsKey($o)){ $OwnerData[$o] = @() }
    $OwnerData[$o] += @{ GroupName = $sg.DisplayName; Members = $members }
}
}$SG_ITRows = Build-ColumnMatrix -MapDisplayToMembers $SG_MapForIT
— Distribution Lists —
$DLs = Get-DistributionGroup -ResultSize Unlimited | Where-Object { $_.RecipientTypeDetails -eq ‘MailUniversalDistributionGroup’ }
$DL_MapForIT = @{}foreach($dl in $DLs){$members = Get-DistributionGroupMember -Identity $dl.Identity -ResultSize Unlimited | Select-Object -ExpandProperty PrimarySmtpAddress$owners  = (Get-DistributionGroup -Identity $dl.Identity).ManagedBy | ForEach-Object { (Get-Recipient -Identity $_ -ErrorAction SilentlyContinue).PrimarySmtpAddress }$owners  = $owners | Where-Object { $_ } | ForEach-Object { $_.ToLower() }
if($TargetOwner -and ($owners -notcontains $TargetOwner)){ continue }

$DL_MapForIT[$dl.DisplayName] = $members
foreach($o in $owners){
    if(-not $OwnerData.ContainsKey($o)){ $OwnerData[$o] = @() }
    $OwnerData[$o] += @{ GroupName = $dl.DisplayName; Members = $members }
}
}$DL_ITRows = Build-ColumnMatrix -MapDisplayToMembers $DL_MapForIT
====== PER OWNER FILE & EMAIL ======
foreach($owner in $OwnerData.Keys){if($TargetOwner -and $owner -ne $TargetOwner){ continue }
$filePath = Join-Path $BaseOwner_Members ("${owner}_Groups_${DateSuffixTight}.xlsx")
$first = $true
foreach($grp in $OwnerData[$owner]){
    $sheet = $grp.GroupName -replace '[\\/:*?"<>|]','_'
    (New-OwnerSheetData -SheetName $grp.GroupName -Members $grp.Members) | Export-Excel -Path $filePath -WorksheetName $sheet -AutoSize -Append:(!$first)
    $first = $false
}
}
====== MASTER REPORT FOR IT =====
if($TargetOwner){$UnifiedPath = Join-Path $BaseUnified_IT (“Unified_Groups_Report_${DateSuffixTight}.xlsx”)if(@($M365_ITRows).Length -gt 0){$M365_ITRows | Export-Excel -Path $UnifiedPath -WorksheetName ‘M365Groups’ -AutoSize}if(@($SG_ITRows).Length -gt 0){$SG_ITRows   | Export-Excel -Path $UnifiedPath -WorksheetName ‘SecurityGroups’ -AutoSize -Append}if(@($DL_ITRows).Length -gt 0){$DL_ITRows   | Export-Excel -Path $UnifiedPath -WorksheetName ‘DistributionLists’ -AutoSize -Append}<#if($M365_ITRows.Count -gt 0){$M365_ITRows | Export-Excel -Path $UnifiedPath -WorksheetName ‘M365Groups’ -AutoSize}if($SG_ITRows.Count -gt 0){$SG_ITRows   | Export-Excel -Path $UnifiedPath -WorksheetName ‘SecurityGroups’ -AutoSize -Append}if($DL_ITRows.Count -gt 0){$DL_ITRows   | Export-Excel -Path $UnifiedPath -WorksheetName ‘DistributionLists’ -AutoSize -Append}#>}
Disconnect-ExchangeOnline -Confirm:$falseWrite-Host ‘Process complete.’ -ForegroundColor Green
The above script throws error as shown in below screenshot and this script is fetching data from O365 cloud groups but gives error of Active Directory as both are synced using ADConnect feature.

Error in Text Format:Active Directory rejected paged search cookie because a cookie handle was discarded by a Domain Controller or a different LDAP connection was used on subsequent page retrieval.Additional information: The parameter is incorrect.

Well … that’s a BIG chunk of code to digest … and the error message is pretty much unreadable …

So before we continue could you please go back to your question, edit it once again and fix the formatting of your code and post the plain text of your error message formatted as code as well instead of the image of it?

When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

Guide to Posting Code - Redux <---- Click :point_up_2:t4: :wink:

( !! Sometimes the preformatted text button hides behind the settings gear symbol. :wink: )

@Olaf Sorry for the pain I have made you suffered through. I have edited the code as well as pasted error in plain text. I hope you will help me through this.

Hello,

Maybe you saw your screen copy contains two parts, in yellow considerations about using a module, in white an error message, more precisely a cookie error.

This one contains an encouraging sentence: Page search needs to be restarted and it will succeed. Did you try that?

I appreciate your effort but you managed to mess it up even more. :index_pointing_up:

Why did you format almost every single line separately? And why did you format your question as code as well? And why did you post only a small part of the error message? :man_shrugging: :man_shrugging:

Apart from that … did you read the notice from @Gloops? … have you tried following the advice you’ve got from your system?

Hi @Gloops,

I am not aware how to do that as I am a newbie to Active Directory. So don’t know how to restart it?

Hello,

I can think of two places to look for that:

  • the documentation of Active Directory (did you try the F1 key ?)
  • ask a search engine for “Active Directory restart a search”

The results may be disappointing, in which case asking here is the following step.

A proposal from a total newbie: what about restarting the service?

Or launch the search instruction again.

I guess that in this case a “total newbie proposal” is only to be tried “just in case”.

***

I see your problems with message formatting.

The normal way to operate is

  • type your question
  • click on the “preformatted text” button (or press Ctrl E as I see in the tooltip)
  • in the field that appears, paste your code

I do not see any possibility to edit the begin / end tags for the preformatted field.

Now that you formatted line by line, maybe the most simple is to redo everything from start, after having saved your text in an external editor, and during edition of your message erase everything before restarting.

Do not forget to save your text first, it would be frustrating to have to re-type everything.

If you want to insert a screen copy, your message will be composed of three parts:

  • your question
  • your code
  • the screen copy

Your question must not be formatted, except if some words are to be outlined.

Your code must be in a preformatted field.

Your screen copy must be uploaded with the … “Upload” button, that looks like a picture.

When possible, it is better to quote an error message in text mode (“blockquote”), this will be more readable by people who use text readers (maybe you have a good view, but some people do not have that luck).

Probably the documentation of Active Directory will show you how to copy the text of the error message. Otherwise, you can consider having a look at Powertoys (except if you find a more specific tool), with that `Windows Shift T` allows you to select a part of a picture, that will be converted to text. Do not forget to read the text, and correct it if needed.

Tried for F1 and also searched in search engine no luck!

OK, so this leaves you time for the formatting question :slight_smile:

I difficultly imagine that relaunching a request from Active Directory is a big question, but let us work with readable questions.

FWIW, here’s a reformatted version of the OPs script:

param([string]$TargetOwner = "user@domain.com")
$ErrorActionPreference = 'Stop' 
$ProgressPreference = 'SilentlyContinue'
$SendOwnerEmails = $true
$SendITEmail = $true
$DateSuffixTight = (Get-Date).ToString('dd-MM-yyyy_hh-mm_tt')
$DateSuffixDL = (Get-Date).ToString('dd-MM-yyyy hh-mm tt').Replace(':', '-')
$BaseOwner_Members = 'C:\psscr\UnifiedGroups'
$BaseUnified_IT = 'C:\psscr\UnifiedGroups\ReportforIT'
$allFolders = @($BaseOwner_Members, $BaseUnified_IT)
foreach ($f in $allFolders) { if (-not (Test-Path $f)) { New-Item -ItemType Directory -Path $f -Force | Out-Null } }
$ITRecipients = @('test@test.in')
# ========== MODULES & AUTH ========
Import-Module ImportExcel
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline
Connect-AzureAD
function New-OwnerSheetData { 
    param([string]$SheetName, [string]$Members)
    foreach ($m in $Members) { 
        [PSCustomObject]@{ $SheetName = $m } 
    } 
}
function Build-ColumnMatrix { 
    param([hashtable]$MapDisplayToMembers)
    $headers = $MapDisplayToMembers.Keys
    $maxRows = ($MapDisplayToMembers.Values | 
                    ForEach-Object { $_.Count }
               ) | 
                    Measure-Object -Maximum | 
                        Select-Object -ExpandProperty Maximum
    $rows = @()
    for($i = 0; $i -lt $maxRows; $i++) { 
        $row = [PSCustomObject]@{} 
        foreach ($h in $headers) { $members = $MapDisplayToMembers[$h]
            $value = if ($members.Count -eq 1 -and $i -eq 0) { 
                        $members 
                     } 
                     elseif ($i -lt $members.Count) {
                        $members[$i] 
                     } 
                     else {
                        '' 
                     }
            $row | Add-Member -MemberType NoteProperty -Name $h -Value $value -Force 
        }
        $rows += $row 
    }
    return $rows 
}
# ======== DATA COLLECTION ========
$TargetOwner = $TargetOwner.ToLower()   # normalize once$OwnerData = @{}$M365_ITRows = @(); $SG_ITRows = @(); $DL_ITRows = @()
# -- M365 Groups --
$M365_allGroups = Get-UnifiedGroup -ResultSize Unlimited | 
                    Where-Object { 
                        $_.ResourceProvisioningOptions -Contains 'Team' -or 
                        $_.AccessType -In @('Private', 'Public') -or 
                        ($_.ResourceProvisioningOptions.Count -eq 0) 
                    }
$M365_MapForIT = @{}
foreach ($g in $M365_allGroups) {
    $members = Get-UnifiedGroupLinks -Identity $g.Identity -LinkType Members -ResultSize Unlimited | 
        Select-Object -ExpandProperty PrimarySmtpAddress
    $owners  = Get-UnifiedGroupLinks -Identity $g.Identity -LinkType Owners  -ResultSize Unlimited | 
                    Select-Object -ExpandProperty PrimarySmtpAddress
    $owners  = $owners | 
        ForEach-Object { 
            $_.ToLower() 
        }
    if ($TargetOwner -and ($owners -notcontains $TargetOwner)) { 
        continue 
    }

    $M365_MapForIT["$($g.DisplayName) ($($g.PrimarySmtpAddress))"] = $members
    foreach ($o in $owners) {
        if (-not $OwnerData.ContainsKey($o)) { 
            $OwnerData[$o] = @() 
        }
        $OwnerData[$o] += @{ GroupName = $g.DisplayName; Members = $members }
    }
}
$M365_ITRows = Build-ColumnMatrix -MapDisplayToMembers $M365_MapForIT
# -- Security Groups --
$mailEnabledSGs = Get-DistributionGroup -ResultSize Unlimited | 
                    Where-Object { 
                        $_.RecipientTypeDetails -EQ 'MailUniversalSecurityGroup' 
                    }
$nonMailSGs = Get-AzureADGroup | 
                Where-Object { 
                    $_.SecurityEnabled -EQ $true -and 
                    -Not $_.MailEnabled -and 
                    ($_.GroupTypes -NotContains 'Unified') -and 
                    ($_.GroupTypes -notcontains 'DynamicMembership') 
                }
$SG_MapForIT = @{}
foreach ($sg in $mailEnabledSGs) {
    $members = Get-DistributionGroupMember -Identity $sg.Identity -ResultSize Unlimited | 
                    Select-Object -ExpandProperty PrimarySmtpAddress
    $owners  = (Get-DistributionGroup -Identity $sg.Identity).ManagedBy | 
                    ForEach-Object { 
                        (Get-Recipient -Identity $_ -ErrorAction SilentlyContinue).PrimarySmtpAddress 
                    }
    $owners  = $owners | 
                    Where-Object { $_ } | 
                        ForEach-Object { 
                            $_.ToLower() 
                        }
    if ($TargetOwner -and ($owners -notcontains $TargetOwner)) { 
        continue 
    }

    $SG_MapForIT[$sg.DisplayName] = $members
    foreach ($o in $owners) {
        if (-not $OwnerData.ContainsKey($o)) { 
            $OwnerData[$o] = @() 
        }
        $OwnerData[$o] += @{ GroupName = $sg.DisplayName; Members = $members }
    }
}
foreach ($sg in $nonMailSGs) {
    $members = Get-AzureADGroupMember -ObjectId $sg.ObjectId | 
                    Select-Object -ExpandProperty UserPrincipalName
                    $owners  = Get-AzureADGroupOwner -ObjectId $sg.ObjectId | 
                        Select-Object -ExpandProperty UserPrincipalName
                    $owners  = $owners | 
                        Where-Object { $_ } | 
                            ForEach-Object { $_.ToLower() }
    if ($TargetOwner -and ($owners -notcontains $TargetOwner)) { 
        continue 
    }

    $SG_MapForIT[$sg.DisplayName] = $members
    foreach ($o in $owners) {
        if (-not $OwnerData.ContainsKey($o)) { 
            $OwnerData[$o] = @() 
        }
        $OwnerData[$o] += @{ GroupName = $sg.DisplayName; Members = $members }
    }
}
$SG_ITRows = Build-ColumnMatrix -MapDisplayToMembers $SG_MapForIT
# -- Distribution Lists --
$DLs = Get-DistributionGroup -ResultSize Unlimited | 
            Where-Object { $_.RecipientTypeDetails -eq 'MailUniversalDistributionGroup' }
$DL_MapForIT = @{}
foreach ($dl in $DLs) {
    $members = Get-DistributionGroupMember -Identity $dl.Identity -ResultSize Unlimited | Select-Object -ExpandProperty PrimarySmtpAddress
    $owners = (Get-DistributionGroup -Identity $dl.Identity).ManagedBy | 
                    ForEach-Object { 
                        (Get-Recipient -Identity $_ -ErrorAction SilentlyContinue).PrimarySmtpAddress 
                    }
    $owners = $owners | 
                    Where-Object { $_ } | 
                        ForEach-Object { 
                            $_.ToLower() 
                        }
    if ($TargetOwner -and ($owners -notcontains $TargetOwner)) { 
        continue 
    }

    $DL_MapForIT[$dl.DisplayName] = $members
    foreach ($o in $owners) {
        if (-not $OwnerData.ContainsKey($o)) { 
            $OwnerData[$o] = @() 
        }
        $OwnerData[$o] += @{ GroupName = $dl.DisplayName; Members = $members }
    }
}
$DL_ITRows = Build-ColumnMatrix -MapDisplayToMembers $DL_MapForIT
# ====== PER OWNER FILE & EMAIL ======
foreach ($owner in $OwnerData.Keys) {
    if ($TargetOwner -and $owner -ne $TargetOwner) { 
        continue 
    }
    $filePath = Join-Path $BaseOwner_Members ("${owner}_Groups_${DateSuffixTight}.xlsx")
    $first = $true
    foreach ($grp in $OwnerData[$owner]) {
        $sheet = $grp.GroupName -replace '[\\/:*?"<>|]', '_'
        (New-OwnerSheetData -SheetName $grp.GroupName -Members $grp.Members) | 
            Export-Excel -Path $filePath -WorksheetName $sheet -AutoSize -Append:(!$first)
        $first = $false
    }
}
# ====== MASTER REPORT FOR IT =====
if ($TargetOwner) {
    $UnifiedPath = Join-Path $BaseUnified_IT ("Unified_Groups_Report_${DateSuffixTight}.xlsx")
    if (@($M365_ITRows).Length -gt 0) { 
        $M365_ITRows | Export-Excel -Path $UnifiedPath -WorksheetName 'M365Groups' -AutoSize 
    }
    if (@($SG_ITRows).Length -gt 0) { 
        $SG_ITRows   | Export-Excel -Path $UnifiedPath -WorksheetName 'SecurityGroups' -AutoSize -Append 
    }
    if (@($DL_ITRows).Length -gt 0) { 
        $DL_ITRows   | Export-Excel -Path $UnifiedPath -WorksheetName 'DistributionLists' -AutoSize -Append 
    }
    <
    # if($M365_ITRows.Count -gt 0){$M365_ITRows | Export-Excel -Path $UnifiedPath -WorksheetName 'M365Groups' -AutoSize}
    # if($SG_ITRows.Count -gt 0){$SG_ITRows   | Export-Excel -Path $UnifiedPath -WorksheetName 'SecurityGroups' -AutoSize -Append}
    # if($DL_ITRows.Count -gt 0){$DL_ITRows   | Export-Excel -Path $UnifiedPath -WorksheetName 'DistributionLists' -AutoSize -Append}
    # }
    Disconnect-ExchangeOnline -Confirm:$false
    Write-Host 'Process complete.' -ForegroundColor Green

I replaced the smart-quotes, inserted the missing “_” character where necessary so “$.” is now $_. , and reformatted those very long lines, indented the where/if/foreach-object blocks, etc. It should be a lot easier to read.

EDIT: added a missing “#”, and used in-line code in the text part of the post so the “dollar-sign underbar period” wasn’t swallowed by the normal editor.

First off, the original post is still largely unreadable. @RichMath did a good job of formatting the code as one readable code block. Use them as an example.

Looking at the error message picture we can see that the error message is specifically coming from the Get-UnifiedGroupLinks cmdlet.

If it were me, I would focus on just that line. Pic a group, and try to run your Get-UnifiedGroupLinks code against that one group and see if the error occurs or not.
I’m not finding a lot when i search for that cmdlet online and the error message.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.