Error with powershell command to delete emails through Purview

EBER Alexis 0 Reputation points
2025-04-24T14:08:41.3566667+00:00

Hello folks !

For security reason, I have to delete emails from a mailbox time to time.
Therefore, I created this script below in Powershell to be run every day with a scheduled task.

Everything works fine, despite numerous problem due to lack of rights that I resolved, except when it comes to delete those emails.

It throws me this error :

Write-ErrorMessage : |Microsoft.Exchange.Management.Tasks.ComplianceJobTaskException|Unable to execute the task. Reason: The search "Messages_scans_suppression" is still running or it didn't return 
any results. Please wait until the search finishes or edit the query and run the search again.
Au caractère C:\Users\XXX\AppData\Local\Temp\tmpEXO_ltltarxx.uae\tmpEXO_ltltarxx.uae.psm1:1189 : 13
+             Write-ErrorMessage $ErrorObject
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [New-ComplianceSearchAction], ComplianceJobTaskException
    + FullyQualifiedErrorId : [RequestId=8ace4e0d-9213-86c8-a828-3e35111e4532,TimeStamp=Thu, 24 Apr 2025 13:59:16 GMT],Write-ErrorMessage

Here is my script :

# ID application (client)
$clientID = "XXXX"
# Emprunte du certificat
$clientThumbprint = "XXXXX"

Import-Module ExchangeOnlineManagement

# Connexion en utilisant un certificat 
try{
    # Security&Compliance
    Connect-IPPSSession -AppId $clientID -CertificateThumbprint $clientThumbprint -Organization "myorg.onmicrosoft.com" -ShowBanner:$false
    }
catch
    { throw $_.Exception}

# Recherche des messages à supprimer
$Search=New-ComplianceSearch -Name "Messages_scans_suppression" -ExchangeLocation "******@XXX.org" -ContentMatchQuery 'kind:email'

Start-ComplianceSearch -Identity $Search.Name

# Attente de la fin d'exécution de la recherche
while((Get-ComplianceSearch $Search.Name).Status -ne "Completed")
{
    echo "attente execution job"
    Get-ComplianceSearch -Identity $Search.Name | FL name,items,size,jobprogress,status
    Start-Sleep -Seconds 10
    
}

Get-ComplianceSearch -Identity $Search.Name | FL name,items,size,jobprogress,status

Echo "Suppression"

Get-ComplianceSearch -Identity "Messages_scans_suppression" | Select *
(Get-ComplianceSearch -Identity "Messages_scans_suppression").Items

# Suppressions des courriels
New-ComplianceSearchAction -SearchName "Messages_scans_suppression" -Purge -PurgeType HardDelete -Confirm:$false


# Suppression de la recherche, car 1 seule recherche portant ce nom là peut exister
Remove-ComplianceSearch -Identity "Messages_scans_suppression" -Confirm:$false

# Déconnexion
Disconnect-ExchangeOnline -Confirm:$false

Here is the full console output :

attente execution job


Name        : Messages_scans_suppression
Items       : 0
Size        : 0
JobProgress : 0
Status      : Starting



attente execution job


Name        : Messages_scans_suppression
Items       : 0
Size        : 0
JobProgress : 0
Status      : Starting



attente execution job


Name        : Messages_scans_suppression
Items       : 0
Size        : 0
JobProgress : 0
Status      : Starting



attente execution job


Name        : Messages_scans_suppression
Items       : 0
Size        : 0
JobProgress : 0
Status      : Starting



attente execution job


Name        : Messages_scans_suppression
Items       : 0
Size        : 0
JobProgress : 0
Status      : Starting



attente execution job


Name        : Messages_scans_suppression
Items       : 0
Size        : 0
JobProgress : 0
Status      : Starting



attente execution job


Name        : Messages_scans_suppression
Items       : 0
Size        : 0
JobProgress : 0
Status      : Starting





Name        : Messages_scans_suppression
Items       : 0
Size        : 0
JobProgress : 100
Status      : Completed



Suppression


Language                              : 
StatusMailRecipients                  : {}
LogLevel                              : Suppressed
IncludeUnindexedItems                 : True
ContentMatchQuery                     : kind:email
SearchType                            : EstimateSearch
HoldNames                             : {}
SearchNames                           : {}
RefinerNames                          : {}
Region                                : 
Refiners                              : 
Items                                 : 0
Size                                  : 0
UnindexedItems                        : 0
UnindexedSize                         : 0
SuccessResults                        : {}
SearchStatistics                      : {"ExchangeBinding":{"Search":{"Name":null,"Sources":"0","SourcesRaw":0,"ContentItems":0,"ContentSize":"0 
                                        B","ContentSizeRaw":0,"HasFaults":false},"Queries":[{"Name":"_PrimaryQuery","Sources":"0","SourcesRaw":0,"ContentItems":0,"ContentSize":"0 
                                        B","ContentSizeRaw":0,"Query":"kind:\"email\"","Type":"Primary"},{"Name":"_UnindexedQuery","Sources":"0","SourcesRaw":0,"ContentItems":0,"ContentSize":"0 
                                        B","ContentSizeRaw":0,"Query":"((kind:\"email\") AND (((IndexingErrorCode\u003c0) OR (IndexingErrorCode\u003e0) OR 
                                        (IsPartiallyIndexed=True))))","Type":"Unindexed"}],"Sources":[]}}
Errors                                : 
ErrorTags                             : {}
NumFailedSources                      : 0
JobId                                 : f5e34838-2064-4e41-dffb-08dd8338047b
Name                                  : Messages_scans_suppression
CreatedTime                           : 24/04/2025 13:57:57
LastModifiedTime                      : 24/04/2025 13:58:51
JobStartTime                          : 24/04/2025 13:57:59
JobEndTime                            : 24/04/2025 13:58:51
Description                           : 
CreatedBy                             : FFO
RunBy                                 : FFO
TenantId                              : XXX
NumBindings                           : 0
Status                                : Completed
ExchangeLocation                      : {******@XXX.org}
PublicFolderLocation                  : 
SharePointLocation                    : 
OneDriveLocation                      : 
ExchangeLocationExclusion             : 
PublicFolderLocationExclusion         : 
SharePointLocationExclusion           : 
OneDriveLocationExclusion             : 
JobRunId                              : 3600ac93-c5e3-4e2d-e4d3-08dd833805e3
Retry                                 : False
AllowNotFoundExchangeLocationsEnabled : False
JobOptions                            : 304
JobProgress                           : 100
CaseId                                : 
CaseName                              : 
PagingState                           : 
Identity                              : 3600ac93-c5e3-4e2d-e4d3-08dd833805e3
ContentURL                            : 
ResultInEOP                           : False
AzureBatchFrameworkEnabled            : True
IsValid                               : True
ObjectState                           : New

0

Write-ErrorMessage : |Microsoft.Exchange.Management.Tasks.ComplianceJobTaskException|Unable to execute the task. Reason: The search "Messages_scans_suppression" is still running or it didn't return 
any results. Please wait until the search finishes or edit the query and run the search again.
Au caractère C:\Users\XXX\AppData\Local\Temp\tmpEXO_ltltarxx.uae\tmpEXO_ltltarxx.uae.psm1:1189 : 13
+             Write-ErrorMessage $ErrorObject
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (:) [New-ComplianceSearchAction], ComplianceJobTaskException
    + FullyQualifiedErrorId : [RequestId=8ace4e0d-9213-86c8-a828-3e35111e4532,TimeStamp=Thu, 24 Apr 2025 13:59:16 GMT],Write-ErrorMessage

In order to resolve this issue, I went to Purview to see if my compliance search was created. It is.
But, when I look up for details, I don't see the "target" as specified in my script with the argument "-ExchangeLocation ******@XXX.org" :

image

Any help would be appreciated :)

Microsoft Security Microsoft Purview
{count} votes

1 answer

Sort by: Most helpful
  1. Chandra Boorla 14,510 Reputation points Microsoft External Staff Moderator
    2025-04-24T16:53:35.36+00:00

    @EBER Alexis

    Thanks for sharing the script and output. The error you are encountering indicates that the compliance search you created is still running or did not return any results, which is why the purge action fails with the following message:

    "The search is still running or it didn't return any results. Please wait until the search finishes or edit the query and run the search again."

    In your case, the search did complete, but since it found 0 items, there was nothing to delete.

    Here are few troubleshooting steps that might help you to fix the issue:

    Please add a condition to check if any items were found before triggering the purge action. Here’s a snippet you can add after the search completes:

    $searchResult = Get-ComplianceSearch -Identity $Search.Name
    
    if ($searchResult.Items -gt 0) {
        Write-Output "Found $($searchResult.Items) items. Proceeding with purge..."
        New-ComplianceSearchAction -SearchName $Search.Name -Purge -PurgeType HardDelete -Confirm:$false
    } else {
        Write-Warning "No items found in the search '$($Search.Name)'. Skipping purge."
    }
    

    This will prevent the purge command from failing when there are no matching emails.
    Confirm Search Completion - Double-check that the compliance search status is actually marked as "Completed" before the purge starts. From the logs you shared, it seems the job took some time to finish, and the purge might have been initiated a bit early.

    Add a Delay or Retry Logic - Even if the search status turns to "Completed", sometimes it takes a few extra seconds for the results to be available. Consider adding a small delay after the status is "Completed" before triggering the purge:

    Start-Sleep -Seconds 15  # Add a short wait before purge
    

    Validate Your Query - Make sure the query 'kind:email' is returning results. You can try running a broader search, like:

    -ContentMatchQuery 'Received:>=04/01/2024'
    

    If no results are found, the purge will fail with the same message you saw.

    Check Your Permissions - Ensure that your account has both of these roles assigned in Microsoft Purview:

    • Compliance Search
    • Search and Purge

    These are required to create searches and delete content.

    Check Mailbox Configuration - Make sure that Single Item Recovery isn’t enabled for the mailbox, as this could prevent permanent deletions.

    I hope this information helps. Please do let us know if you have any further queries.

    Kindly consider upvoting the comment if the information provided is helpful. This can assist other community members in resolving similar issues.

    Thank you.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.