Windows – Tasks on Scheduler won’t start with files on OneDrive/Sharepoint (Powershell)

powershellscheduled-taskswindows

I have a powershell script that opens an Excel file every day in the morning, runs a macro and closes. This was working fine until recently that we moved our legacy network drives to Sharepoint Online.

The script, if I run it manually, starts and does what it has to do. However, when I place it on Task Scheduler it doesn't open the file.

I have tried to:

  • Placing the script outside my OneDrive folder: The script runs but the file won't open.
  • Placing both script and file outside OneDrive and Sharepoint: The script runs and the file opens.
  • With both in OD/SP, run a task scheduler to open a Powershell window and running the script from there: The first window opens but Powershell closes when running the second script.

The user that runs the Task, myself, has full control over the folders where both script and file are located and, as mentioned, in all these cases the script works if it's ran manually. I don't seem to be able to find anything on the internet, nor on the logs (Unless I#m blind there aren't any logs created after all the previous tasks ran), and I'm starting to run out of hairs to pull.

Does anyone have any idea/advise?

Thanks!

Best Answer

Task Scheduler PowerShell script not running

Based on what you describe and what I see in the XML file per your configuration where you have. . .

<Exec>
  <Command>"C:\Path\To\OneDrive - Company Ltd\Scripts\pwsh\DonwloadOpen.ps1"</Command>
  <Arguments>-ExecutionPolicy Bypass</Arguments>
<Exec>

I think that needs to be configured like this instead to execute the PowerShell from Task Scheduler. . .

<Exec>
  <Command>Powershell</Command>
  <Arguments>-ExecutionPolicy Bypass -File "C:\Path\To\OneDrive - Company Ltd\Scripts\pwsh\DonwloadOpen.ps1"</Arguments>
</Exec>

So from the Action tab you will create an Action defined as:

  • Action: Start a program
  • Program/script: Powershell
  • Add arguments (optional): -ExecutionPolicy Bypass -File "C:\Path\To\OneDrive - Company Ltd\Scripts\pwsh\DonwloadOpen.ps1"
  • Start in (optional): C:\Windows\System32\WindowsPowerShell\v1.0 enter image description here

Furthermore, some of these options in your case may help but based on the security and your configuration, I'm not 100% they are needed but easy enough to test. . .

From the General tab of the scheduled task, be sure the Run whether user is logged on or not and the Run with highest privileges options are both selected.

enter image description here

Additional Resources


Related Question