Trying to create a delete email powershell script

291 Views Asked by At

I am new to powershell scripting and I am trying to create a script that I can tweak as needed to delete phishing emails from exchange.
So far I have this:

Import-Module ExchangeOnlineManagement
Connect-IPPSSession -UserPrincipalName [email protected]
        
New-ComplianceSearch -Name Test1 `
-ExchangeLocation All `
-ContentMatchQuery 'subject:"Informational-severity alert: eDiscovery search started or exported" AND sent:08/31/2021'
        
Start-ComplianceSearch -Identity Test1
        
Get-ComplianceSearch -Identity Test1
        
New-ComplianceSearchAction -Searchname Test1 -Purge -PurgeType Softdelete

The script works up until the purge line due to the fact that the compliance search is still in progress. So how can I adjust the script to have it wait until the compliance search is complete before running the purge on the emails? Again, I am very much a beginner at powershell, so take that into consideration when writing an answer, please!

1

There are 1 best solutions below

0
On

Use the Start-Job command to start a task, and then run the Wait-Job command to wait for the job to finish before continuing to the next command in your script.

From the PowerShell documentation Start-Job https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/start-job?view=powershell-7.1
Wait-Job https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/wait-job?view=powershell-7.1