'Delete mails that have been received before the date given by the user using powershell

I am unable to delete mails that have been received before the date given by the user. The code I used is,

$date = Read-Host "Enter the date (dd/mm/yyyy)"
Search-Mailbox -Identity "[email protected]" -SearchQuery { received<=$date} -DeleteContent -Force

Its showing error as, The KQL parser threw an exception.

  • CategoryInfo : InvalidArgument: (:) [], ParserException
  • FullyQualifiedErrorId : [Server=DM4PR12MB5360,RequestId=297f7526-fe64-43ec-916b-cbd2e3c19cb1,TimeStamp=21-02-2022 08:29:53] [FailureCategory=Cmdlet-ParserException] 5E9AB73F
  • PSComputerName : outlook.office365.com

But when I directly use the date without storing it in variable like below it works.

Search-Mailbox -Identity "[email protected]" -SearchQuery { received<=17-02-2022} -DeleteContent -Force

Can anyone tell why its working when I am directly using the date in cmdlet and not working when stored in variable and used.

Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source