Run a batch file with Windows task scheduler - windows-7

I have a batch file daily.bat, this is the code:
cd C:\inetpub\wwwroot\infoweb\factuur\cron
c:\PHP\php.exe -f ./cron_pdf.php
ftp -s:ftp_upload.txt ftp.site.be
And I created a task with task scheduler in Windows 7. When I run the batch manually, everything goes fine, but when I try to run it with the task scheduler nothing happens.
My action is
'run script' "C:\inetpub\wwwroot\site\x\cron\daily.bat"
UAC is off and I am Admin.
Any idea why this is not working?

I faced the same problem, but I found another solution without having to modify my batch script.
The only thing that I missed out is at the 'Action' settings - "Start in (Optional)" option.
Go the task properties --> Action tab --> Edit --> Fill up as below:
Action: Start a program
Program/script: path to your batch script e.g. C:\Users\beruk\bodo.bat
Add arguments (optional): <if necessary - depending on your script>
Start in (optional): Put the full path to your batch script location e.g. C:\Users\beruk\(Do not put quotes around Start In)
Then Click OK
It works for me. Good Luck!

None of the above method worked. I tried it this way as said it in a tutorial and it worked.
Action:
Start a program
Program/script:
cmd
Add arguments:
/c start "" "E:\Django-1.4.1\setup.bat"
Worked for me on Win7 Pro. You must have an account with a password (blank passwords are no good)

For those whose bat files are still not working in Windows 8 and 10+ Task Scheduler , one thing I would like to add to Ghazi's answer - after much suffering:
Under Actions, Choose "Create BASIC task", not "Create Task"
That did it for me, plus the other issues not to forget:
Use quotes, if you need to, in your Start a program > program/script entry i.e "C:\my scripts\runme.bat" (or just use the Browse button)...
Use the Start In path to your batch file, even though it says optional - BUT DON'T use quotes in the Start In field. (Crazy but true!)
This worked without any need to trigger a command prompt. And it is the quickest and simplest method.
(Sorry my rep is too low to add my Basic Task tip to Ghazi's comments)

Make sure "Start In " has NO QUOTES.

It is working now. This is what I did. You probably won't need all these steps to make it work but just to be sure try them all:
Check the account parameters of your scheduled task and make sure they are set to run whether or not someone is logged into the machine
check run with most privileges/rights
Make sure you go to the full path first: cd C:\inetpub\wwwroot\infoweb\factuur\cron
Don't use double quotes in your batch files (don't know why but seems to help)
Be super admin, enter 'Net user administrator /active:yes' in command prompt, log out and log in as the super admin, so UAC is off

Make sure "Start In" does NOT end with a BACKSLASH.

My script was to pull latest code from master and publish a new branch
cd D:\dev\repo
git checkout master
git pull
git branch -D my-branch
git push origin --delete my-branch
git checkout -b my-branch
git push -u origin my-branch
exit

Had an issue where my task was not firing simply because it was running on a laptop without a power cord... Under the conditions tab, by default it is checked so that a task will not run while AC power is not connected.

Under Windows7 Pro, I found that Arun's solution worked for me: I could get this to work even with "no user logged on", I did choose use highest priveledges.
From past experience, you must have an account with a password (blank passwords are no good), and if the program doesn't prompt you for the password when you finish the wizard, go back in and edit something till it does!
This is the method in case its not clear which worked
Action: start a program
Program/script : cmd
(doesn't need the .exe bit!)
Add arguments:
/c start "" "E:\Django-1.4.1\setup.bat"

I messed with this for several hours and tried many different suggestions.
I finally got it to work by doing the following:
Action: Start a program
Program/Script: C:\scriptdir\script.bat
Add arguments (optional) script.bat
Start in (optional): c:\scriptdir
run only when user logged in
run with highest privileges
configure for: Windows Vista, Windows Server 2008

If all of the rest fails for you here ensure that the user you are trying to run the task as has access to the file you're trying to use.
In my case I was trying to run a batch file from C:\Users\Administrator\Desktop which the account couldn't access. Moving it to a neutral location on C:\ resolved the issue.

I post the answer to this question here and here.

Using the Run button in the Task Scheduler main window to test several variations finally found the correct settings. This two options must be combined:
-Run only when user is logged on
-Run with highest privileges.
All other variations failed. It's infuriating all the time wasted on this, but at least it works.
OS: WINDOWS 8 CORE (BASIC) VERSION

Please check which user account you use to execute our task. It may happen that you run your task with different user then your default user, and this user requires some extra privileges.
Also it may happen that the task is executed but you cant see any effect because the batch file waits for some user response so please check task manager if you see your process running.
Once it happen that I schedule a batch with svn update of some web page and the process hangs because svn asked for accepting server certificate.

Don't use double quotes in your cmd/batch file
Make sure you go to the full path start in (optional):
C:\Necessary_file\Reqular_task\QDE\cmd_practice\

Try run the task with high privileges.
put a \ at the end of path in "start in folder" such as c:\temp\
I do not know why , but this works for me sometimes.

Action: Start a Program
Program/script: C:\Windows\System32\cmd.exe
Add arguments: /k start "" "E:\scripts\example.bat"
Add exit to the end of your batch file.
The cmd window will not show if you select Run whether user is logged in or not. You need to select Run only when user is logged on to see the window in action.

Related

run curl from windows task scheduler automatically

I have a simple one line bat file that runs a curl localhost:port. My curl.exe is in the same folder as the bat I don't have it installed globally. It runs fine if I double click it, it also runs fine if I right click in task scheduler and select run task. It also says it completes the "scheduled tasks" successfully but nothing happens (I'm sure of this as I'm checking data that should update if the script is run, and it doesn't happen under the scheduled/automatic scenarios). After reading lots of users issues I tried configuring in two ways (all on 5 minute updates):
Common Way
Action: Start a Program
Program/script: C:\p\updater.bat
Start in: C:\p\
Other Way
Action: Start a Program
Program/script: cmd
Add arguments: /c start "" "C:\p\updater.bat"
I have set permissions to the bat and the containing folder to allow all for all users/etc. Neither work when automatically triggered, neither error. I've tried in Server 2008 and Windows 10 (my OS) mode. Both work if I right click run task, neither automatically, any ideas?
Default working directory for scheduled script is %Windows%\system32. Try to add in first line to you updater.bat:
cd c:\p\
For diagnostic, you can add output redirect to you commands in bat file:
echo Script Started >> c:\p\log.txt
curl SomeCommand SomeCommand >>c:\p:\curloutput.txt
echo Script Ended >> c:\p\log.txt
and check files log.txt and curloutput.txt after execution of your script

SVN update using windows task scheduler not working

I want to setup a windows cron job to update svn. I created a batch file with this step:
START TortoiseProc.exe /command:update /path:"C:\svn" /closeonend:0
and setup the task scheduler to run this daily. This svn requires a password which I want to enter each time rather than cache it. The batch file works as expected without any issues.
The task scheduler shows that the job was successfully executed. However, I don't get the GUI to enter the password, neither does the directory get updated. Also, when I tried to manually update the svn directory thereafter, it says that svn is locked.
Why is task scheduler reporting successful?
Why is svn getting locked?
Task scheduler reports success because START seems to return exit code 0. START only starts an application and exits. It doesn't wait until the started application has exited. The task scheduler never sees the exit code of TortoiseProc this way.
You can do this with START WAIT. Enter START /? in a CMD for more information.
You can also do this with CMD /K itself. Enter CMD /? in a CMD for more information.
But I don't think you need START or CMD at all. You can either run TortoiseProc directly or call it via a batch script. In the batch script you can add more debugging like echos and redirected output in files to see what happens.
Do not use TortoiseProc.exe for this task! Use Subversion command-line client (svn.exe). Read the docs:
Remember that TortoiseSVN is a GUI client, and this automation guide
shows you how to make the TortoiseSVN dialogs appear to collect user
input. If you want to write a script which requires no input, you
should use the official Subversion command line client instead.

Running batch file at Windows 7 UNLOCK

I have a very simple .bat file. It only has one line:
powercfg -h off
What this does is turn off the computer's ability to hibernate. It works fine when I double click the file. I can confirm this by going into the command prompt and typing "powercfg /a", which shows me that hibernate is indeed off. The problem is that this batch file doesn't seem to be running at logon even though it's in my Startup folder.
I've tested it by turning hibernate on using the command prompt ("powercfg -h on") and then actually putting my computer into hibernation. Then I turn it back on and log in to Windows. But when I open a command prompt and type "powercfg /a" it shows me that hibernate is still on. It seems the batch file doesn't run at logon even though it is in my Startup folder.
I've also tried making it run from a task scheduled to run at logon, but that didn't work either.
Some ideas:
Make sure you set the Start in and Program/script options of the batch file correctly.
If (1) doesn't work then try moving the .bat file to a directory with basic permissions.
Try to schedule the execution of the batch file like this cmd /c "c:\path\batch.bat"
Also take a look at this: Batch runs manually but not in scheduled task.
I got it to work using Task Scheduler. The problem was that I was using the trigger "At log on," when I should have chosen "On workstation unlock."
It's obvious to me now, but I didn't think of it at the time: hybernating didn't actually log me off, it only locked me out.

Open Excel on Jenkins CI

I am working on Windows 7 (logged in as session no.1), my Jenkins CI is running as windows service in session 0.
My problem is.. I want to open an Excel file through Jenkins CI in session 0, but want to display its GUI on session 1.
I know that session 0 is isolated in Windows 7, but is it possible to run a process in session 0 and then output in another session? please help.
Edit:
Took a little trial and error, but this is what finally worked for me (Windows 7 64-bit).
Download PsTools from Microsoft site
We only need psexec.exe, but you can extract everything. Extract to some location accessible by Jenkins, preferably without spaces in the path.
Open elevated command prompt: type cmd into Start's quicksearch, right click cmd.exe, select Run as Administrator.
Type C:\path\to\psexec.exe -accepteula and press enter.
Type C:\path\to\psexec.exe -i 1 cmd and press enter. (If you see a command prompt appear, all is good, close it now)
In Job configuration, configure Execute Windows Batch command step
Write the following:
C:\path\to\psexec.exe -accepteula && C:\path\to\psexec.exe -i 1 cmd /c start C:\PROGRA~2\MICROSO~1\path\to\excel.exe
Where:
C:\path\to is your full path to psexec.exe, unless it is in your %path%
-i 1 is the session ID that you want to launch in.
C:\PROGRA~2\MICROSO~1\path\to is your full path to excel.exe without spaces. Since most Office installations are going to be under paths with spaces, like "Program Files (x86), you have to figure out the short path, or place it somewhere without spaces.
Having excel.exe under %path% and working from regular command line was not enough.
A little explanation for those that care:
psexec needs to install a services first. For that, it needs to be run from elevated command prompt for the first time. This is a one-time installation step.
To make psexec work, you need to accept the EULA prompt. This is done per session/user. So even if you run psexec -accepteula in your command prompt, it doesn't help when Jenkins service (running as Local System in session 0) tries to use it. Therefore, you have to place that into the Jenkins job, along with the command. Technically, it only needs to be there once, and can be removed afterwards, but it definitely doesn't hurt to keep it there.
I've used cmd /k and running this command from my local cmd prompt to debug. This is what made me realize I couldn't find a way to escape the spaces (tried various quoting), so had to resort to short file names. Note that short file names are not required, this is just to escape spaces.
no its not-
plus any UI interactions requires you to run Jenkins as Java web start rather than a service or you can not interact with UI elements.

Powershell script does not run via Scheduled Tasks

I have a small script on my Domain Controller that is setup to email me via SMTP about the latest Security Event 4740.
The script, when executed manually, will run as intended; however, when setup to run via Scheduled Tasks, and although it shows to have been executed, nothing happens (no email).
The script is as follows:
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
$Event = Get-EventLog -LogName Security -InstanceId 4740 -Newest 5
$MailBody= $Event.Message + "`r`n`t" + $Event.TimeGenerated
$MailSubject= "Security Event 4740 - Detected"
$SmtpClient = New-Object system.net.mail.smtpClient
$SmtpClient.host = "smtp.domain.com"
$MailMessage = New-Object system.net.mail.mailmessage
$MailMessage.from = "fromemail#domain.com"
$MailMessage.To.add("toemail.domain.com")
$MailMessage.IsBodyHtml = 1
$MailMessage.Subject = $MailSubject
$MailMessage.Body = $MailBody
$SmtpClient.Send($MailMessage)
Scheduled Task is setup as follows:
RunsAs:LOCAL SYSTEM
Trigger: On event - Log: Security, Event ID: 4740
Action: Start Program - C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Argument: -executionpolicy bypass c:\path\event4740.ps1
I have also tried the following:
Trigger: On event - Log: Security, Event ID: 4740
Action: Start Program - C:\path\event4740.ps1
According to the Tasks History: Task Started, Action Started, Created Task Process, Action Completed, Task Completed. I have looked through some various links on the site with the same 'issue' but they all seem to have some sort of variable that I do not have. I have also tried some of the mentioned solutions thinking they may be somewhat related, but alas nothing is working. I have even tried removing my Scheduled Task and resetting it as mentioned here: http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx
Has anyone run into this type of error before or know how to bypass this issue?
Troubleshooting:
I decided to try an call a .bat file via a scheduled task. I created a simple file that would echo the current date/time to a monitored folder. Running the file manually and via a task triggered by the 4740 Event achieved desired results. Changing the .bat file to instead call the .ps1 file worked manually. When triggered by the 4740 Event, now the .bat will no longer run.
Change your Action to:
powershell -noprofile -executionpolicy bypass -file C:\path\event4740.ps1
On a Windows 2008 server R2: In Task Scheduler under the General Tab -
Make sure the 'Run As' user is set to an account with the right permissions it takes to execute the script.
Also, I believe you have the "Run only when user is logged on" Option checked off. Change that to "Run whether user is logged on or not". Leave the Do Not Store password option unchecked, and you'll probably need the "Run with Highest Privileges" option marked.
NOTE: Please ensure that you select Create a Basic task Action and NOT the Create Task Action.
I found the following solution:
1) Make powershell.exe run as administrator for this
right-click on the powershell.exe icon
click on properties under the shortcut key menu
click on the advance button; check that "run as administrator" is
checked.
2) in the task scheduler window under the action pane add the
following script as a new command
%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -ExecutionPolicy Bypass -noexit -File "C:\ps1\BackUp.ps1"
Although you may have already found a resolution to your issue, I'm still going to post this note to benefit someone else. I ran into a similar issue.
I basically used a different domain account to test and compare. The task ran just fine with "Run whether user is logged on or not" checked.
A couple of things to keep in mind and make sure of:
The account being use to execute task must have "Logon as batch job" rights under the local security policy of the server (or be member of local Admin group). You must specified the account you need to run scripts/bat files.
Make sure you are entering the correct password characters
Tasks in 2008 R2 don't run interactively specially if you run them as "Run whether user is logged on or not". This will likely fail specially if on the script you are looking for any objects\resource specific to a user-profile when the task was created as the powershell session will need that info to start, otherwise it will start and immediately end.
As an example for defining $Path when running script as "Run whether user is logged on or not" and I specify a mapped drive. It would look for that drive when the task kicks off, but since the user account validated to run task is not logged in and on the script you are referring back to a source\object that it needs to work against it is not present task will just terminate.
mapped drive (\server\share) x:\ vs. Actual UNC path \server\share
Review your steps, script, arguments. Sometimes the smallest piece can make a big difference even if you have done this process many times. I have missed several times a character when entering the password or a semi-colon sometimes when building script or task.
Check this link and hopefully you or someone else can benefit from this info: https://technet.microsoft.com/en-us/library/cc722152.aspx
If you don't have any error messages and don't know what the problem is - why PowerShell scripts don't want to start from a Scheduled Task do the following steps to get the answer:
Run CMD as a user who has been set for Scheduled Task to execute the PowerShell script
Browse to the folder where the PowerShell script is located
Execute the PowerShell script (remove all statements that block the error notifications if any exists inside of the script like $ErrorActionPreference= 'silentlycontinue')
You should be able to see all error notifications.
In case of one of my script it was:
"Unable to find type [System.ServiceProcess.ServiceController]. Make sure that the assembly that contains this type is loaded."
And in this case I have to add additional line at the begining of the script to load the missing assembly:
Add-Type -AssemblyName "System.ServiceProcess"
And next errors:
Exception calling "GetServices" with "1" argument(s): "Cannot open Service Control Manager on computer ''. This operation might require other privileges."
select : The property cannot be processed because the property "Database Name" already exists
Good morning,
I know this is an old thread but I just ran across it while looking for a similar problem - script was running successfully but not doing its work. I can't find the post that helped me but my issue was that I was running the script as the domain admin. When I followed the suggestion of the post and added the domain admin to the local administrator's group it worked. I hope this helps others with the same issue I had.
Joe
Implemented the ExecutionPolicy Bypass argument to get the scheduled task working.
Program: Powershell.exe
Add Arguments: -ExecutionPolicy Bypass -File C:\pscommandFile.ps1
Found successful workaround that is applicable for my scenario:
Don't log off, just lock the session!
Since this script is running on a Domain Controller, I am logging in to the server via the Remote Desktop console and then log off of the server to terminate my session. When setting up the Task in the Task Scheduler, I was using user accounts and local services that did not have access to run in an offline mode, or logon strictly to run a script.
Thanks to some troubleshooting assistance from Cole, I got to thinking about the RunAs function and decided to try and work around the non-functioning logons.
Starting in the Task Scheduler, I deleted my manually created Tasks. Using the new function in Server 2008 R2, I navigated to a 4740 Security Event in the Event Viewer, and used the right-click > Attach Task to this Event... and followed the prompts, pointing to my script on the Action page. After the Task was created, I locked my session and terminated my Remote Desktop Console connection. WIth the profile 'Locked' and not logged off, everything works like it should.
In addition to advices from above I was getting error and found solution on following link http://blog.vanmeeuwen-online.nl/2012/12/error-value-2147942523-on-scheduled.html.
Also this can help:
In task scheduler, click on the scheduled job properties, then settings.
In the last listed option:
"if the task is already running, the following rule applies:"
Select "stop the existing instance" from the drop down list.
I think the answer to this is relevant too:
Why is my Scheduled Task updating its 'Last Run Time' correctly, and giving a 'Last Run Result' of '(0x0)', but still not actually working?
Summary: Windows 2012 Scheduled Tasks do not see the correct environment variables, including PATH, for the account which the task is set to run as. But you can test for this, and if it is happening, and once you understand what is happening, you can work around it.
One more idea that worked. It's really silly, but, apparently, the default target OS setting (bottom right corner of the screen) is Vista / Windows Server 2008. As we're past the 10 year mark, it is likely that your Powershell script will not be compatible to these.
Changing the target to Windows Server 2016, as shown on the screenshot below, did the trick for me.
I was having almost the same problem as this but slightly different on Server 2012 R2. I have a powershell script in Task Scheduler that copies 3 files from one location to another. If I run the script manually from powershell, it works like a charm. But when run from Task Scheduler, it only copies the first 2 small files, then hang on the 3rd (large file). And I was also getting a result of "The operator or administrator has refused the request". And I have done almost everything in this forum.
Here is the scenario and how I fixed it for me. May not work for others, but just in case it will:
Scenario:
1. Powershell script in Task Scheduler
2. Ran using a domain account which is a local admin on the server
3. Selected 'Run whether user is logged on or not"
4. Run with highest priviledges
Fix:
1. I had to login to the server using the domain account so that it created a local profile in C:\Users.
2. Checked and made user that the user has access to all the drives I referred to on my script
I believe #1 is the main fix for me. I hope this works for others out there.
In my case (the same problem) helped to add -NoProfile in task action command arguments and check checkbox "Run with highest privileges", because on my server UAC is on (active).
More info about it
enter link description here
I have another solution for this problem that might apply to some of you.
After I created my power shell (xyz.ps1) script, I opened it in notepad for subsequent editing. Hence Windows made an association between my xyz.ps1 file with notepad.exe and Scheduler was trying to run my power shell script (xyz.ps1) with notepad.exe in the background instead of executing it in Powershell. I found this problem by paying close attention to "Display all running tasks" section in the scheduler, which showed that notepad.exe was being used to run the xyz.ps1 script. To verify this, I right clicked on my xyz.ps1 file in windows explorer, went to "Properties", and it showed Notepad against the "Opens With" section. Then I changed the "Opens With" to %SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe. This did the trick. Now the scheduler would execute my xyz.ps1 using powershell.exe and gave me the desired results.
To locate your powershell.exe, refer to this article:
https://www.powershelladmin.com/wiki/PowerShell_Executables_File_System_Locations
I had very similar issue, i was keeping the VSC window with powershell script all the time when running the schedule task manually. Just closed it and it started working as expected.
I had the same issue, while running the couple of scripts. When i execute it manually from task scheduler, The script was executing flawlessly.
But it was not executing at the scheduled time automatically.
The following resolution worked for me
Find the location of the powershell exe , Right click and go to security options,Add the "Authenticated users" to the group or user names and give full control.
Once this is done wait for the script to executed.
If youu are having this problem under WIN 10 this might solve your problem as it did for me. An update messed up the task scheduler.
http://answers.microsoft.com/en-us/windows/forum/windows_10-performance/anniversary-update-version-1607-build14393-breaks/d034ab52-5d49-4b92-976a-a1355b5a6e6d?page=2
This comment solved my problem.
Your tip about "one-time" tasks works great - it will definitely be
sufficient as a workaround until MS fixes the issue. The only
advantage to "daily" as far as I can see is that lack of the arbitrary
date associated with the run time. It might be confusing to others as
to why the job is set to start on X date.
Trigger settings "Einmal" means "one-time", "Sofort" means "At once"
In my case it was related to a .ps1 referral inside the ps1 script which was not signed (you need to unblock it at the file properties) , also I added as first line:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force
Then it worked
My fix to this problem was to ensure I used the full path for all files names in the ps1 file.
I had a similar problem where only half the script would run using task scheduler, but would run fine under the same account running the script manually. The problem was I was referencing my own module. When I added the functions directly to my script file, the task scheduler worked, but when I used the module task scheduler failed. The same coded (module) running under the same account worked fine without task scheduler.
I think this was some type of issue with how windows handles environment variables doing a run as. When I referenced the module via the full path (instead of module name) it worked from task scheduler.
after trying a lot of time...
task scheduler : powershell.exe -noexit & .\your_script.ps1
be sure to put your script in this folder : windows\system32
good luck !

Resources