Running PowerShell in Task Scheduler - windows

I am using PowerShell for downloading data from email.
I want to run this process by PowerShell. When I run script like this:
D:\script.ps1
in powershell.exe it works fine.
When I schedule it in Task Scheduler nothing happens.
I tried it to Set it like Program/script:
powershell
Powershell.exe
powershell.exe
Add arguments:
-executionpolicy bypass -file D:\script.ps1
-file D:\script.ps1
-file "D:\script.ps1"
And nothing works. I'm using Windows 2008 R2.

Troubleshooting scheduled tasks is a pain in the rear, because you can't really see what's going on. These are some things you may want to check:
Check that your commandline works in principle, e.g. by running it from CMD (in your case try running powershell.exe -File "D:\script.ps1"). If that gives you any errors you need to fix those first.
If you intend to run the task as a particular user, start CMD as that user and run the same commandline to check if the user has all the permissions required for whatever the script is doing.
Check if your task actually terminated or if the process is still running (via Process Explorer, Get-Process, Task Manager, …).
Check the Last Run Result for the exit code of the command.
Enable the history for your scheduled tasks (Action → Enable All Tasks History). That will give you at least some information about what the task is doing, whether it starts at all, and if/which errors occurred. You need administrative rights to enable the task history.
Check the eventlog for errors/warnings correlating with the task run.
Add logging statements to the script you're running to record progress information. Personally I prefer logging to the eventlog, because that avoids filesystem permissions issues.
Write-EventLog -LogName Application -Source EventSystem -EventID 100 -EntryType Information -Message 'Your log message.'
If you have admin privileges on the system you can register an event source of your own and use that in the above log statement instead of abusing an existing source like EventSystem:
New-EventLog -Source MyEventSource -LogName Application
Further help will depend heavily on the findings you got following these steps as well as your actual script code.

I found this site that was quite useful:
http://www.microsoftpro.nl/2011/07/07/how-to-schedule-a-powershell-script-using-scheduled-tasks-in-windows-server-2008-r2/
I also changed Secure option property and it helped.
I didnt check: Do not store password and now it runs without me being logged into network.
Peace

Few major observations which I had faced:
Instead of giving only powershell.exe , try giving the full PS path C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.
Permission is one more concern. The user through which you are running the task might not have the permission to run that.
Execution Policy: Make sure you are bypassing the execution policy using -ExecutionPolicy Bypass.
Make sure you are running the task with Highest Privileges.
Finally, through analysis of logs.

Related

Service Recovery "Run a Program" not working

Unable to fire command (or file) when a service crashes/fails.
I have a script that I can run manually that emails me event logs that match search criteria. When I set said service to run a program using the following parameters:
Program:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Command line Parameter:
-ExecutionPolicy Bypass -File C:\PowerShell_Scripts\tftp_restarttftpd_restart.ps1
I've also tried just echoing some text to a file as well as send-mailmessage in Command Line Parameter. I've also used the -Command suffix. None work.
I trigger the service failure buy capturing the PID and running taskkill against it. I see the service fail but no email triggers.
I've looked for events to indicate the script was at least attempted but I don't see anything.
Help appreciated.

Powershell script scheduled using Task scheduler doesn't run...script runs fine

I am using windows 8.
I have the following script file (that spits our all services to a CSV file). When I run this as follows from powershell editor, it works fine.
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe C:\Powershell\SchedulingaScript.ps1
When I schedule this script from windows task scheduler it won't kick off.
I have "Unrestricted" execution policy set on that session. Following is the code in the script file and 2 images are the setting on the task scheduler.
#Trying out scheduling powershell scripts
Get-Service | Export-CSV "C:\ExportingServicestoaCSVFile.CSV"
You have to use the -file Parameter. Simply enter powershell -? and you will see all possible options to launch powershell.
Hope this helps -tom
In the Edit Action dialog Program box simply put PowerShell. In Arguments put -file "C:\sciptlocation\scriptname.ps1"

Powershell Task Scheduler Stuck Running

I was trying to test a simple powershell script with task scheduler, the status showed running but the powershell console never showed up.
My ps1 script just contains two simple commands:
dir
pause
Here is my setup:
General
Run whether user is logged on or not (check)
Run with highest privileges (check)
Actions
Action: Start a program
Program/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments (optional): -file E:\iQ_Schedule\Untitled1.ps1
This setup works on other computer (Windows 10) but just won't on this one (Windows Server 2012 R2). I am not sure why.
Welcome to Session 0 isolation mode.
When you run your task with "Run whether user logged in or not", it runs in so called session 0. You can check this with your task manager.
Tasks running is Session 0 has restrictions on showing the user interface
This could be due to the user account which is running the script. When the script is running with the SYSTEM account, the script will run in the background.
Try to change the option 'When running the task, use the following user account' to the account you are currently logged on with. Then the PowerShell console should pop up.
It sounds like the Windows Server 2012 R2 could have PSversion 2. The Pause function doesn't exist until PSversion 3.
Could you give the value of this command to us?
$PSVersionTable.PSVersion
Run whether user is logged on or not, will still give you the prompt. If the Hidden option is checked, you will not see the prompt.
I have also seen that the user that is trying to run the PowerShell script inside Task Scheduler doesn't have access to the folder strucutre. Make sure the user that is running the Task Scheduler has access to E:\iQ_Schedule\.
Make sure the user that is running the task scheduler has read access to the file structure you are trying to look up.
You can run as SYSTEM user, but then use the executionpolicy bypass argument
Powershell -ep Bypass 'e:\myPSFile.ps1' -myArg1 'arg1' -myArg2 'arg2'

Windows 10 - Task Scheduler - Not running (0x41303)

I'm trying to schedule a task in Windows 10, on the event of "At log on" in order to start several programs, but it won't run after several trial/error. The task is configured as follows:
General: Run whether user is logged on or not (it prompted the credentials inputbox, also tried Run only when user is logged on). Run with highest privilegies. Configure for Windows 7 and Windows 10 options where tried.
Triggers: At log on, any user, enabled (tried specific user too).
Actions: Start a program, which are "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "C:\Program Files\Internet Explorer\iexplore.exe" (this one has Add Arguments: %HOMEDRIVE%%HOMEPATH%), "D:\ids\sqldeveloper\sqldeveloper\bin\sqldeveloper64W.exe". The route were copy/paste from the shortcut properties of each program.
Conditions: No condition were set.
Setting: No additional settings.
History: disabled.
When I restart and log on, nothing happens. Checking the status panel appears the summary of the task, where in the Last Run Time is 30/11/1999 12:00:00 a.m., the Last Run Result is (0x41303), and Status column is Ready.
Tried to look others questions, but seems to be others problems. What am I missing? Is there another configuration that I must apply? Thanks in advance.
I had this problem as well (Windows Server 2019), with error 0x41303 and Last Run Time set to 30/11/1999.
When I changed the start time to a future time instead of past (i.e. 2 minutes from current time), the scheduled task ran successfully (result: 0x0) and repeated just fine per the trigger.
Task Scheduler 0x41303: Task has not yet run.
The main reason for this is if the scheduler's first run is set in the past or simply hasn't run yet. To fix:
Try running it manually or
Set the next trigger in the near future.
The last run result should update indicating it ran but if it still doesn't run, check the task conditions.
A full list of task scheduler return codes
Try open "trigger" tab, and edit the trigger detail.
I found here my trigger was not enabled, I've just enabled it.
This could generate error 0x41303.
Got the same error code when scheduling a python script, fixed it by changing Conditions > Network to "Any connection" or disabling it entirely.
I had spaces in my script that was being called and had to change it to have quotes around it. Maybe this will help someone
Use "&&" in between the commands instead of commas and as far as possible try to give the absolute path to the arguments, hope this helps.
OR
You can create a ".bat" file with the different commands in it.
I think there's several possible reasons for this Last Run Result code. If you enable the task History and try running the scheduled task manually, you can check the History tab for events and should be able to get more information, such as an error code or error reason. Once you have that, you should be able to Google for the specific error message that you're getting.
In my case the run user (-User) was disabled and I constantly receive the code 267011 (0x41303). To check it run Get-LocalUser.
Setting the trigger start further into the future didn't seem to help. While not always going to be the right solution, running the task as SYSTEM got rid of 0x41303 for me.
$script = { "hello world" | write-host }
$registerJob = {
param($script)
$taskName = "Hello World"
Unregister-ScheduledJob -Name $taskName -ErrorAction Ignore
$job = Register-ScheduledJob -Name $taskName -ScriptBlock $([scriptblock]::create($script)) -RunEvery $([TimeSpan]::FromMinutes(1)) -MaxResultCount 1
$psSobsSchedulerPath = "\Microsoft\Windows\PowerShell\ScheduledJobs";
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount
$someResult = Set-ScheduledTask -TaskPath $psSobsSchedulerPath -TaskName $taskName -Principal $principal
}
# Run as Administrator needed in order to call Register-ScheduledJob
powershell.exe -command $registerJob -args $togglePowerOverlay
On General Tab:
Choose "Run whether user is logged on or not"
Tick "Run with highest priviledge"
On Trigger Tab:
Make sure status is "Enabled"
In my case I launch task using another domain account but this account doesn't had rights for this. I added rights for launch task using this instruction.

Scheduled task & PowerShell Script not being executed

I know this has been asked a 1000 times and I think I looked through all of them.
I have scheduled tasks running PowerShell Scripts on other servers already, but not on this server. Which has me scratching my head as to why I can't get it to work on this server.
I have a powershell script on a Windows 2008 R2 server. I can run it manually and it all works perfectly, but when I try to run it from a scheduled task the History says it was run, but the PowerShell script does not execute.
PSRemoting is enabled
The server ExecutionPolicy is "RemoteSigned"
I get two entries in the History
Action completed
Task Scheduler successfully completed task "\Processing" , instance "{dbbd4924-42d6-4024-a8ed-77494c7f84cf}" , action "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.EXE" with return code 0.
Task complted
Task Scheduler successfully finished "{dbbd4924-42d6-4024-a8ed-77494c7f84cf}" instance of the "\Processing" task for user "domain\user".
The Scheduled Task looks like this:
I set to run under my account while I'm logged on. (since I can run the script manually as myself already)
checked Run with highest privileges.
trigger is to run every 10 minutes
Start a program Action.... Powershell.exe
Arguments: -executionpolicy remotesigned -File D:\abc\def\powershell\Processing.ps1
Conditions & Settings default settings.
Ensure that you're not being blocked by a permission issue with the task:
http://blogs.technet.com/b/askperf/archive/2012/04/18/task-scheduler-error-a-specified-logon-session-does-not-exist.aspx
The above GPO prevents credentials from being saved. Other User Rights Assignment settings can prevent things being run as batch/script/task/etc.
As a workaround, you can also set the task to run a .bat file with the powershell task. Adding an echo or pipe parameter may give you some clues to the issue.
I would recommend that you should add some diagnostic logging to this script to find out a place that causes this issue or redirect output of this script to a file. E.g. change your string with arguments this way:
-executionpolicy remotesigned -File D:\abc\def\powershell\Processing.ps1 2>&1 d:\output.log
Looks like that the script is executed, but something goes wrong. There are too many reasons for such behavior and it is difficult to find the root cause without a code.

Resources