I have a powershell script that manages my outlook inbox. It iterates through all messages in the inbox and tags, moves or deletes them. I ran this script and everything worked fine (PS 5.1). But when I tried to run it with task scheduler it didn’t delete mails (tagging and moving still worked fine).
I log with psframework and have a try catch block in my script so I should see any errors thrown, but there are none. It runs without errors but just doesn’t delete mails.
Here is the scheduled task configuration:
- security:
- user: my user account
- Run only when user is logged on
- actions:
- program/script: C:coderun-ps.vbs
- arguments: C:CodeoutlookRules.ps1
Here is the vbs that starts the ps script:
(I use this so I get real windowstyle hidden and not having the console pop up briefly every time)
Set shell = CreateObject("WScript.Shell")
For Each arg In WScript.Arguments
shell.Run("powershell -windowstyle hidden -executionpolicy bypass -noninteractive -command ""&"" ""'" & arg & "'"""),0
Next
Here is part of the ps script:
#requires -modules psframework
function Add-Category($message, $category) {
if ($message.Categories -notmatch $category) {
$message.Categories += ",$category"
$message.Save()
Write-PSFMessage "Added '$category' category to email with subject '$($message.Subject)'." -Level Host
}
}
function Move-ToArchive($message) {
$subject = $message.subject
$message.move($archive) | Out-Null
Write-PSFMessage "Archived message with subject '$subject'" -Level Host
}
function Remove-Message($message) {
$subject = $message.subject
$message.Delete()
Write-PSFMessage "Deleted message with subject '$subject'" -Level Host
}
# Setting up logging
$paramSetPSFLoggingProvider = @{
Name = 'logfile'
InstanceName = '<taskname>'
FilePath = 'C:CodeLogsoutlookRulesoutlookRules-%Date%.log'
FileType = 'CMTrace'
Enabled = $true
Wait = $true
}
Set-PSFLoggingProvider @paramSetPSFLoggingProvider
# Setting up Outlook comObject and getting inbox mails
$outlook = New-Object -ComObject Outlook.Application
$namespace = $outlook.GetNamespace("MAPI")
$inbox = $namespace.GetDefaultFolder(6)
$archive = $namespace.GetDefaultFolder(39)
$messages = $inbox.Items
$messages.Sort("[ReceivedTime]", [bool]$true)
Write-PSFMessage "===== Processing $($messages.Count) messages. =====" -Level Host
foreach ($message in $messages) {
if ($message.Class -eq 43) {
try {
$senderAddress = switch ($message.Sender.Type) {
'SMTP' { $message.Sender.Address }
'EX' { $message.Sender.GetExchangeUser().PrimarySmtpAddress }
Default { 'NOTFOUND' }
}
$subject = $message.Subject
$body = $message.Body
# this works
if ($senderAddress -eq '[email protected]') {
Add-Category $message 'test'
}
# this works
elseif ($body -match ".*test.*") {
Move-ToArchive $message
}
# this doesn't work
elseif ($subject -eq 'testsubject') {
Remove-Message $message
}
}
catch{
Write-PSFMessage -Level Warning "Error processing email with subject '$subject': $_"
}
}
}
Wait-PSFMessage