I have been dealing with this particular issue all day to no avail.
I setup a Task within Task Scheduler to execute a .ps1 file in the following location "C:\Program Files\WindowsPowerShell\Modules\\.ps1" The task is executed by a service account that has admin privileges to the server. However the task always executes but the script fails. This may sound odd but it seems like all of the functions contained in the script are not resolving or appear like they are not there. I say this because the first failure that can occur within the script is if the function to invoke a web request fails and return $null data. The script will email me stating $null was returned. I receive the email every time with Null is returned. I tried this again but placing the .ps1 file in a different directory, but that still didn't work out for me. I also tried using the SYSTEM account but that also returned the same result.
Now if I use my own credentials to run the task it works flawlessly. Why is this happening? Any help is appreciated.
Michael, is your web request external? If so is it possible that the issue could be something to do with internet access of the service account. Can you run the script with the service account from a prompt, outside of task scheduler?
I went with your approach, John. I began to run my code line by line and it failed to execute the Invoke-WebRequest cmdlet because the IE Engine was not available or IE's first-launch configuration was not complete for the user. Which makes perfect sense since no one would ever log into a computer as a service account.
I had to add the parameter "-UseBasicParsing" to my Invoke-WebRequest and Wha-la, everything worked! 🙂