Run powershell script with task scheduler as different user

Hello guys,

I have a problem with running powershell script through the task scheduler.

When I manually run open the powershell under the SQL account which have apropriate rights on SQL database it is working properly. Powershell will execute sql script with simple select, export results do xls and send it via email.

When I run the powershell script via task scheduler, script will start and finish, I will get also email with xls, but there are no data. Task scheduler is set to run under SQL account (with this account manual script execution work properly), account have run as a batch job properties etc. I can also see that when the mentioned scheduled task is started, new powershell process is started as well and it is running under SQL account, so for me it is really mystery, why it is not collecting data from SQL database.


$Path = Split-Path -Parent "D:\sccm_report\Report\*.*"
$LogDate = Get-Date -f ddMMyyyy
$Csvfile = $Path + "\Bitlocker_$logDate.csv"
Invoke-Sqlcmd  -InputFile .\sql_script.sql -ServerInstance COMPANY-SCSQL01\CM -Database CM_BA1 |
Export-Csv -Path $Csvfile -Encoding UTF8 -NoTypeInformation

#Email Variables
$fromaddress = "user@test.com"
$toaddress = "user@test.com"
$Subject = "Bitlocker report"
$body = "Bitlocker report"
$attachment = "$Csvfile"
$smtpserver = "maila.company.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)

I already found the fix-maybe it will be helpfull for somebody. It is required to use full path in the Invoke-sqlcmd part of the script:

I used Invoke-Sqlcmd -InputFile .\sql_script.sql -ServerInstance COMPANY-SCSQL01\CM -Database CM_BA1 |

correct syntax is Invoke-Sqlcmd -InputFile D:\SCCM_report\sql_script.sql -ServerInstance COMPANY-SCSQL01\CM -Database CM_BA1 |

Regards,
M

Great that you’ve been able to fix it yourself and thank you very much for sharing. :+1:t4: :slightly_smiling_face:

Have a great Weekend. :wink: