Forum Discussion

venkatkirankona's avatar
venkatkirankona
Brass Contributor
Jul 20, 2023

How to Clear Discovery Holds Folder (Version 2)

Step 1: Exclude the ID on the Compliance Retention Policy using the below-mentioned commands. 

 

1: Connect-IPPSSession

 

2: Set-RetentionCompliancePolicy -Identity <RetentionPolicyName> -AddExchangeLocationException user

 

or

 

Set-RetentionCompliancePolicy -Identity <RetentionPolicyName> -AddExchangeLocationException user1, user2

 

or

 

Set-RetentionCompliancePolicy -Identity <RetentionPolicyName> -AddExchangeLocationException user1, user2, user3

 

Step 2: Use the Script below to get it excluded. I have added one more tab for giving the output with clear instructions as before and after running the command. Later, this command will send the output file to me as an email with an attachment and also make a copy of that output file to my Onedrive Synced location. 

1: Connect-ExchangeOnline

2:

function ProcessMailbox($email) {
# Get the initial DiscoveryHolds data
$initialData = Get-MailboxFolderStatistics -Identity $email -ResultSize unlimited | Where-Object {$_.Name -eq 'DiscoveryHolds'} | select name,foldersize
$exchangeGuid = (Get-Mailbox -Identity $email).ExchangeGuid

# Run the commands
Set-Mailbox -Identity $email -RetainDeletedItemsFor 0

for($i=0; $i -lt 80; $i++){
try {
Start-Managedfolderassistant -Identity $email
Start-Sleep -Seconds 1 # Wait for 1 second
} catch {
Write-Warning "Unable to process $email due to error: $($_.Exception.Message)"
}
}

Set-Mailbox $email -RemoveDelayHoldApplied
Set-Mailbox $email -RemoveDelayReleaseHoldApplied

for($i=0; $i -lt 80; $i++){
try {
Start-Managedfolderassistant -Identity $email
Start-Sleep -Seconds 1 # Wait for 1 second
} catch {
Write-Warning "Unable to process $email due to error: $($_.Exception.Message)"
}
}

# Get the final DiscoveryHolds data
$finalData = Get-MailboxFolderStatistics -Identity $email | Where-Object {$_.Name -eq 'DiscoveryHolds'} | select name,foldersize

# Add the data to the results
$results = New-Object PSObject -Property @{
'User' = $email
'ExchangeGuid' = $exchangeGuid
'Initial DiscoveryHolds Size' = $initialData.FolderSize
'Final DiscoveryHolds Size' = $finalData.FolderSize
}
return $results
}

# Import email IDs from CSV file
$emailIDs = Import-Csv -Path 'CSV Path' | Select-Object -ExpandProperty Distinguishedname

# Create an array to hold the results
$results = @()

foreach($email in $emailIDs) {
# Process the mailbox and add the results
$results += ProcessMailbox -email $email
}

# Get current date in UTC
$utcNow = (Get-Date).ToUniversalTime()

# Define the IST offset
$istOffset = New-TimeSpan -Hours 5 -Minutes 30

# Calculate the current date in IST
$istNow = $utcNow + $istOffset

# Format the IST timestamp
$timestamp = $istNow.ToString("yyyy-MM-dd_HH-mm")

# Define filename with timestamp
$csvPath = "CSV-Path\ExitListoutputreportinitial_$timestamp.csv"

# Export the results to a CSV file
$results | Export-Csv -Path $csvPath -NoTypeInformation

# Filter out email IDs where 'Final DiscoveryHolds Size' is not "0 B (0 bytes)"
$nonZeroEmailIDs = $results | Where-Object { $_.'Final DiscoveryHolds Size' -ne "0 B (0 bytes)" } | Select-Object -ExpandProperty User

# Define the parameters for the email
$emailSmtpServer = "smtp.office365.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "Sender Email ID"
$emailSmtpPass = "Password"
$emailFrom = "Microsoft 365 Assistant <$emailSmtpUser>"
$emailTo = "Recipient Email ID"

# Re-run for non-zero 'Final DiscoveryHolds Size' until all are zero
while($nonZeroEmailIDs) {

# Clear previous results
$results = @()

# Rerun the script for the non-zero mailboxes
foreach($email in $nonZeroEmailIDs) {
$results += ProcessMailbox -email $email
}

# Export the results to a CSV file

# Get the current date in UTC
$utcNow = (Get-Date).ToUniversalTime()

# Define the IST offset
$istOffset = New-TimeSpan -Hours 5 -Minutes 30

# Calculate the current date in IST
$istNow = $utcNow + $istOffset
$finaltimestamp = $istNow.ToString("yyyy-MM-dd_HH-mm")
$finalcsvPath = "CSV-Path\ExitListoutputreportfinal_$finaltimestamp.csv"
$results | Export-Csv -Path $finalcsvPath -NoTypeInformation

# Inform via email that the script is re-running for specific mailboxes
$emailSubject = "Re-running script for specific mailboxes"
$emailBody = "Dear Venkat Sir,

The following mailboxes have a non-zero 'Final DiscoveryHolds Size'. We are re-running the script for these IDs: `n" + ($nonZeroEmailIDs -join ", ")

Send-MailMessage -To $emailTo -From $emailFrom -Subject $emailSubject -Body $emailBody -SmtpServer $emailSmtpServer -Port $emailSmtpServerPort -UseSsl -Credential (New-Object System.Management.Automation.PSCredential ($emailSmtpUser, (ConvertTo-SecureString $emailSmtpPass -AsPlainText -Force))) -Attachments $csvPath

# Check again for non-zero 'Final DiscoveryHolds Size'
$nonZeroEmailIDs = $results | Where-Object { $_.'Final DiscoveryHolds Size' -ne "0 B (0 bytes)" } | Select-Object -ExpandProperty User
}

# Define the destination directory
$destinationDir = "Onedrive System Synced folder path"

try {
# Copy the file to the destination directory
Copy-Item -Path $csvPath -Destination $destinationDir -ErrorAction Stop
Write-Host "Venkat Sir, The Output File is successfully copied to $destinationDir"
} catch {
Write-Error "Venkat Sir, Failed to copy the file to the destination directory $_"
}

# Inform via email that the script is complete
$emailSubject = "Exit List Activity Report - $finaltimestamp"
$emailBody = "Dear Venkat Sir,

 

Please find the attached Activity Output Report.

 

This finalized report contains data both before and after the status of the DiscoveryHolds folder, including the Exchange GUID of the given IDs. Please review it and let us know if any changes are required.

 

This report has also been copied to your synced OneDrive folder at the following path: $destinationDir

 

Have a good day, Sir.

 

Best Regards,
Microsoft365 Admin."

$emailAttachments = $FinalcsvPath

Send-MailMessage -To $emailTo -From $emailFrom -Subject $emailSubject -Body $emailBody -SmtpServer $emailSmtpServer -Port $emailSmtpServerPort -UseSsl -Credential (New-Object System.Management.Automation.PSCredential ($emailSmtpUser, (ConvertTo-SecureString $emailSmtpPass -AsPlainText -Force))) -Attachments $emailAttachments

# Define the destination directory
$destinationDir = "OneDrive Synced Folder Path"

try {
# Copy the file to the destination directory
Copy-Item -Path $finalcsvPath -Destination $destinationDir -ErrorAction Stop
Write-Host "Venkat Sir, The Output File is successfully copied to $destinationDir"
} catch {
Write-Error "Venkat Sir, Failed to copy the file to the destination directory $_"
}

 

Conclusion

 

This command will run continuously until the Discovery Holds folder size is Zero. If it is re-running again and again for more than an hour, please include it in the compliance retention policy again and exclude them after 5-10 Mins(This will happen only in rare cases). 

No RepliesBe the first to reply

Resources