Task Scheduler wont run powershell script that data mines outlook

In short, I have a script that I wrote that is supposed to go through my emails in an outlook folder and download any attachments within the last 24 hrs to a folder on my computer. This task works perfect when I run it from the ISE, command line, or via a batch file. However, when I use the windows task scheduler, no matter how I try to run it, it will say task complete, but the files are not downloaded. I have narrowed down my problem to not being able to access the loop which parses the folder items, but I do not know how to fix it.

I am running powershell 2.0, windows 8.1 and outlook 2007. The task scheduler works fine for other tasks.

code below:

$olFolderInbox = 6
$o = New-Object -comobject outlook.application
$ns = $o.GetNameSpace(“MAPI”)
$inbox = $ns.GetDefaultFolder($olFolderInbox)

foreach($message in $inbox.Items) { #I cannot access this loop
#some code to save the attachments

Thank you in advance.

Hi Derek,

My guesses are that either the user of your scheduled task does not have an Outlook profile configured or you might experience below Task Scheduler bug:



User logged on or not?

what happens if you put this in front of the foreach?

($inbox.items | select -First 1).subject |out-file mailitems.txt

Dan P.,

I have been trying to run the script with the checkbox ticked “run whether user is logged in or not”. I have been actually logged in the entire time.

I also input your line of code.

"($inbox.items | select -First 1).subject |out-file mailitems.txt">

Everything worked fine when I executed your script from the task scheduler. I also made the below changes, replacing the loop with an if statement, but had no luck accessing within the ‘if statement’. Task scheduler doesn’t seem to want to execute powershell loops or if statements.

$message = ($inbox.items | select -First 1)
$message.subject | out-file "C:\folder\mailitems.txt"
if ( $message.Subject -eq "Update"){ 
  #this is the code in the loop

Daniel K.,
I looked into your method as well. I used the batch file script in the link you provided. It did not work either.


Thanks again

This works for me in a scheduled task.

task settings: Run only when user is logged on,
actions program\script = powershell.exe
actions arguments = full path to ps1.

$mail = $inbox.items

$dir = 'c:\temp\mailattachments\'

foreach($message in $mail){

$message.attachments|foreach { 

#$_.filename | out-file c:\temp\attachements.txt -append

$_.saveasfile((Join-Path $dir $_.filename)) 



If it’s set to “run whether user is logged in or not” then it wont run in the current logged in user context meaning said context is either “system” or whatever account you specified.

In both cases you need to make sure an outlook profile has been created for that context.