How to check powershell errors when running powershell from task scheduler

You can use the following method.

Add this to your powershell script in various places

“Start!” | Out-File c:\mylog.txt

then use try/catch method to catch the errors

#Get data from database and export to file
try{

“SQL Starts” | Out-File c:\mylog.txt

YOUR CODE HERE
} catch [Exception]
{
“Error: {0}” -f $_.Exception.Message | Out-File c:\mylog.txt
$error | Out-File c:\mylog.txt
}

“End” | Out-File c:\mylog.txt

then check your error log file for issue.

 

It happens that the script wasn’t always working and after getting it sorted I have found this

Error: The term ‘Invoke-SqlCmd’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Invoke-SqlCmd : The term ‘Invoke-SqlCmd’ is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is

To fix the problem i had to add the following to the begining of the script

# Import the SQL Server Module.
Import-Module Sqlps -DisableNameChecking;

This has fixed the problem.