PowerShell Script Not Running on Scheduled Task – Troubleshooting

powershelltask-schedulerwindows-server-2012-r2

I have been attempting to set up a PowerShell script to run as part of a scheduled task on a Windows Server 2012 R2 server. The script will run if I execute it manually from the GUI but all but one of my attempts to run it from a task have failed.

After some troubleshooting I found that if I set the task to "Run only when the user is logged on" and I execute the task, it runs just fine. It pops a powershell window, runs the script, and closes itself. It seems like I am on the right track and I may have narrowed it down as to what is the problem but I am at a loss as to where to go from here. Obviously, I would like the script to execute regardless of whether or not I am logged in.

Just in case, here is the script I am running:

    Get-ChildItem C:\somefolder -Recurse| 
    Where-Object{$_.PsIsContainer}| Sort-Object CreationTime -desc| 
    Select-Object -Skip 3| Remove-Item -Force

Where can I look from here? I have been able to run powershell scripts in this manner from server 2008 without problems but I just cannot seem to crack this one.

EDIT: For the action of the task set to start a program and under Program/script I have "powershell" then ".\myscript.ps1" for an arguement then "c:\" for start in.

Best Answer

Can you try running with following:

powershell -noprofile -noexit -executionpolicy bypass -file C:\path\script.ps1

Also check that: get-executionpolicy is set to RemoteSigned

Also check "Run whether user is logged on or not.