Powershell script will not run correctly when run from Task Scheduler

I have a script that looks for a specific folder in Outlook, then looks for specific computer names in the subject line.  When it's done it sends me an email of any errors

Because of the problems I was having I send some debugging info to a file.  When I run the script from the Task Scheduler, the subject line is never output to the file which means to me that it never finds the folder.  When I run it via Run or a Powershell window everything is good

The computer names are kept in a txt file
The script is attached, Let me know if you want to see something from the Task Scheduler
clear-host

$computerFoundArray = @()
$computerNotFoundArray = @()
$computerFailedArray = @()

$inputpath = "C:\Bat\Data\computers.txt"
[System.Collections.ArrayList]$computerArray = gc $inputpath

$olFolderInbox = 6
$outlook = new-object -com outlook.application;
$ns = $outlook.GetNameSpace("MAPI");
$inbox = $ns.GetDefaultFolder($olFolderInbox)
$targetfolder = $inbox.Folders | where-object { $_.name -eq "Daily Report" }

$targetfolder.items | foreach {
	foreach ($computer in $computerArray){$debuglog = $debuglog + $_.subject + " = Subject `r`n"
			if($_.subject -match $computer) {
			$computerFoundArray = $computerFoundArray + $computer
		}
	}
	}
foreach ($computer in $computerArray){
	if($computerFoundArray -notcontains $computer){$debuglog = $debuglog + "  " + $computer + " Not Found `r`n"
		$computerNotFoundArray = $computerNotFoundArray + $computer
	}
}

$debuglog | Out-File 'c:\bat\data\debug.txt' -Append
sendDailyJobErrors $computerNotFoundArray
find-missingAcronis

Open in new window

c7c4c7Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Joe Winograd, Fellow&MVEDeveloperCommented:
Try setting "Run with highest privileges" (which runs the script as Administrator, i.e., elevated):

task scheduler run elevated
Regards, Joe
c7c4c7Author Commented:
It is all ready set that way as well as Run whether the user is logged on or not
footechCommented:
Having "Run whether user is logged on or not" is likely your problem.
From my reading trying to use Office COM objects in a non-interactive session is very problematic.  If it works when you uncheck that setting, I wouldn't put any money on getting it to work otherwise.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

Robberbaron (robr)Commented:
is the user you test with the same as the one assigned in the Scheduled Task ?

I have found it necesasry to havce it hust that way as it ensures DLL's etc are registered correctly. ( i created a TaskRunner user for this purpose so they have a local profile)
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
As said above by the other Experts: I'm 100% confident you need to use the same user for the task and interactive, and to run the task only when logged in - you can't open Outlook for the same PST/OST files more than once, so you have to reuse an open Outlook, which again requires to act inside of the current interactive session.
Run with highest privileges might be necessary or not, I cannot tell.
David Johnson, CD, MVPOwnerCommented:
uncheck run with highest privileges as you must run as a user that has an outlook profile.
I put an exit as the last line of the script or it will continue running.

If I run as an administrator
MyDocuments:\WindowsPowerShell\Scripts
$ . 'D:\Documents\WindowsPowershell\Scripts\ee07082016.ps1'
[6,12: New-Object] Retrieving the COM class factory for component with CLSID {00
06F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 
Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FA
ILURE)).
[7,1] You cannot call a method on a null-valued expression.
[8,1] You cannot call a method on a null-valued expression.

MyDocuments:\WindowsPowerShell\Scripts
$ 

Open in new window

I call it from a batch file .. runme.cmd
c:\windows\system32\WindowsPowershell\v1.0\powershell -noprofile d:\Documents\WindowsPowershell\Scripts\ee07082016.ps1
exit

Open in new window

David Johnson, CD, MVPOwnerCommented:
If I set the task to run only when the user is logged in it works whether outlook is open or not.
if task is set to run with highest privileges and outlook is not open it opens in a hidden window
using a try/catch block and the error is
The error message was Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))
if outlook is open
The error message was Retrieving the COM class factory for component with CLSI
D {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 8008
0005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EX
EC_FAILURE)).
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
On W7, PS5 without UAC, I performed a simple test running
$olk = New-Object -Com Outlook.Application
$AdminInbox = $olk.Session.Folders("Administrator@domain.com").Folders("Inbox").Items

$adminInbox.Count | Out-File C:\Temp\EE\test.txt

Open in new window

with
powershell -command "& {start-process powershell '-version 4 -File C:\Temp\EE\test-outlook.ps1' -RedirectStandardOutput c:\Temp\EE\test.log -RedirectStandardError C:\Temp\ee\test-error.log}"

Open in new window

which runs no matter whether Outlook is open, the task is running elevated, or the session is interactive or not. A non-interactive session is much slower, having to start Outlook is much slower too, but that are the only effects I see.
c7c4c7Author Commented:
The user account is the same as the one assigned in the Scheduled Task

Running without the "Run with Highest privileges" selected and "Only when the user logged on" takes care of my problem as stated

It does open a powershell window when it runs, why is that

The script was to run whether I was logged on or not, it runs in the middle of the night.  Any suggestions
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
What's the issue with staying logged in over night?
You can also try if switching to the access way I showed makes a difference (not using MAPI namespace).
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows 10

From novice to tech pro — start learning today.