NottyHeadedGeek

Move Unread Outlook Mails with Specific Subjects

Aug 26th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. CLEAR-HISTORY
  2. CLS
  3. $sSearchSubject = 'Error' #needs to work for multiple Subjects such as Incident, Error, Service request, etc.
  4. $sScope = 'Inbox'
  5. $oOutlook = New-Object -ComObject Outlook.Application
  6. $oNameSpace = $oOutlook.GetNamespace('MAPI')
  7. $oStore = $oNameSpace.Stores['john.doe@contoso.com']
  8. $oInbox = $oStore.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)
  9. $oRootFolder = $oStore.GetRootFolder()
  10. $oTargetFolder = $oRootFolder.Folders['Drafts']
  11.  
  12. $sUnreadInboxMail = $oInbox.Items.Restrict('[UnRead] =   True')
  13. $iInboxMailCount = $oInbox.Items.Restrict('[UnRead] =   True').Count
  14. Write-Host ("The Count of unRead Mails with the Search Character as ""$sSearchSubject"" is $iInboxMailCount") -ForegroundColor Green
  15.  
  16. $sUnreadInboxMail | Select Subject, ReceivedTime
  17.  
  18. #This piece does not work though I know this is the way the coding should be done
  19. #Explanation: - If there are 5 mails with the Subject containing Error NONE get moved.
  20. #I bet I am doing something SILLY but not able to figure it out
  21.  For($iMailCount=($oInbox.count-1);$iMailCount -ge 0;$iMailCount--)
  22.  {
  23.      If ($_.subject -Like "*$sSearchSubject*")
  24.      {
  25.         $($oInbox)[$iMailCount].move($oTargetFolder)
  26.      }
  27.  }
  28.  
  29. #This Piece of Code only moves Certain Mails
  30. #Explanation: - If there are 5 mails with the Subject containing Error only 3 get moved and the rest stay in the Inbox
  31. $oInbox.Items.Restrict('[UnRead] =   True') |
  32.  ForEach-Object {
  33.         If ($_.subject -Like "*$sSearchSubject*") {
  34.             $_.Move($oTargetFolder)
  35.         }
  36. }
Add Comment
Please, Sign In to add comment