Exchange 2010 and O365 search and remove email across all mailboxes – Script Critique request

Hello all – I’m looking for some feedback on a script I’ve been working on. I’m hoping to identify any ways I could improve the script, either via simplifying commands or alternate commands that I may not be aware of.

Context: My org has a requirement that when a user reports receiving a Phishing email, we must search all user mailboxes for further instances of said email and remove it everywhere found.

Script actions:

  • Prompts user for a sender address and subject line, O365 credentials and on-prem Exchange 2010 credentials.
  • Sends a Windows application event log item capturing username that is running the script, and entered sender address & subject line (which is then forwarded to our corporate Splunk)
  • Forces user to input a Subject line if sender provided is an internal address (so we don’t kill everything ever sent by that user)
  • Connects to O365 and starts a compliance search for the provided message.
  • Connects to on-premesis Exchange 2010 environment, and uses start-job -scriptblock against each of the target Exchange servers to run a search-mailbox command (done this way for parallel processing)
  • Deletes all found messages on-prem and in O365.

Specifically, what I’d like to improve on:

Right now to successfully run the on-prem Exchange search, capture a log of the results and delete the messages, it takes each script block about 30 minutes to process. If I could combine the log search and the delete search in a way that does not move all found messages to the target mailbox, I could cut that time in half. Alternatively, if the results from the log search (mailboxes identified in search) could be used as the targets for the deletcontent search then I could also greatly reduce the processing time. I don’t know what sort of returned results are available to be utilized from the search-mailbox command though.

The script: https://pastebin.com/ebxzx5sH

Thank you all for any advice; and feel free to use this script for your own purposes as well.

submitted by /u/insufficient_funds
[link] [comments]

Leave a Reply