Manual vs Task Schedule

So I have ps1 consist of executing .bat file to gather data and output via email.
If I were to run ps1 manually everything works just fine. When it comes to task scheduling, only my headers shows up in my csv file.

Hope my action is correct.
Program/script: powershell
Add arguments: -Executionpolicy Bypass -file “D:\ScheduledTasks\file1.ps1”

Clear-content D:\ScheduledTasks\file1.csv
Clear-content D:\ScheduledTasks\file2.csv
.\orphans_file.bat
clear
$textfile   = 'D:\ScheduledTasks\file1.csv'
$headerfile = 'D:\ScheduledTasks\headers-files.csv'
$(Get-Content $headerfile; Get-Content $textfile) | Set-Content $textfile

###########Define Variables########  
$fromaddress = "do-not-reply@fake.com" 
$toaddress ="me@ps1.com"
$Subject = "Files" 
$body = "Testing ps1 script"
$attachment = "D:\ScheduledTasks\file1.csv" 
$smtpserver = "mail.ps1.com" 
 
#################################### 
$message = new-object System.Net.Mail.MailMessage 
$message.From = $fromaddress 
$message.To.Add($toaddress)  
$message.Subject = $Subject 
$attach = new-object Net.Mail.Attachment($attachment) 
$message.Attachments.Add($attach) 
$message.body = $body 
$smtp = new-object Net.Mail.SmtpClient($smtpserver) 
$smtp.Send($message) 
del file*.csv

Hi

Is is possible to use Export-Csv and Send-MailMessage cmdlet’s? Those would benefit you more in my opinion.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-5.1
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-6

Regards

Jake

Ok, so it worked just like the other form.
it’s the output i’m questioning.
Why my output from Task Scheduler not the same as if I manually run the script?

Could be a permissions issue. Is the task running as the same user that you’re using to test manually?

no. I use system.
I just don’t understand why only step 5,6 and 7 worked. Which is adding the headers.

Hi Peety,
I have had this issue before 9 times out of 10 it’s a permission issue.

Things to try

1 trying running the task schedule command on a blank command prompt Check the output

2 ensure that the user account the tasks is running as has the required permissions and is a a member of run as batch job group

3 run the tasks with the highest privileges

Regards
Shihan

I’ll check again. I just don’t understand why I can’t search and add myself to the “Security Options”

Ok, so I added myself to “Security options: When running the task, use the following user account:”
This is account I ran script manually. Still empty.

You’re invoking the batch file from a relative path. Try this: for the task action, in the “Start in” field, enter “D:\ScheduledTasks”.