I'm using Powershell version 7.2.1
When I run the command below on Powershell, it works fine, i.e. Excel is launched and the target Excel file is opened.
& 'PATH_TO_EXCEL_EXE' 'PATH_TO_TARGET_FILE'
Howewer, when I pass this command to a scheduled task, Excel is launched but the target file isn't opened. More details about my Powershell script:
$action = New-ScheduledTaskAction -Execute "& 'PATH_TO_EXCEL_EXE' 'PATH_TO_TARGET_FILE'"
...
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "myTask"
# The line below is for testing purpose, to see if my scheduled task can launch correctly.
Start-ScheduledTask -TaskName "myTask"
Can someone tell me the reason why Powershell fails to replicate the action, when it's passed to a scheduled task as above? Any workarounds/solutions would be appreciated.
Based on ZivkoK's comment, I'm adding an answer which solves the issue:
$excelExePath = ...
$excelFile = ...
$action = New-ScheduledTaskAction -Execute $excelExePath -Argument """$excelFile"""
A scheduled task based on the action above does what it intends to do.
P.S. Triple quotes surrounding excelFile parameter are needed when the excel file path contains space characters. For example, if the excel file path is "C:\MyUser\some random file.xlsx", then Excel tries to open 3 files named "some", "random", and "file.xlsx". Using triple quotes solves this problem.