Task Scheduled not running batch file - windows

I have file which does somethings and it works fine if I run the file manually but it doesn't run when set up in task scheduler.
Batch file is in a folder on desktop on windows 7.
Any feedback will be helpful.
I've even tried this link solution didn't work.

Most likely in this case you need to make sure that the directory the script runs in ("Start in") is set correctly. Usually this is the same directory that contains your script. You can set this in the Scheduled Task's properties.

As a test, try moving the .bat file to a directory with basic permissions (maybe a shared directory for example).
I had the same problem as you. My .bat file was located in a folder with some restrictive permissions on it, so that only my user account could access it. Even though I had set up the task scheduler to use my credentials it still failed. Moving the .bat file to another directory sorted the issue.

I don't know if this will help, but in bashing my head against one problem after another for far too many hours, I finally got my own batch file to work properly as a scheduled task. Some of the things I learned in the process:
If you are the user who has created the scheduled task, you must also be a user who has logged into the system using a password.
Any reference to a file name, inside the batch file, needs to be the last part of fully qualified path, starting with drive letter.
If you do a comparison, like [%flag%] EQU [0], be aware that the "[" and "]" symbols are string literals that are included in the data that gets compared.
If part of your batch file sets a variable and includes a "FOR" loop that calls a subroutine in which you expect to change the variable, you need to make sure that the variable is originally initialized as early as possible in the batch file. That is, something like this:
IF ... (
SET %flag=0
FOR ... (CALL :subr)
IF [%flag%] EQU [1] ( main scheduled-task command goes here)
)
GOTO :eof
:subr
IF ... (SET %flag=1)
:eof
--worked from the command line, but not as a Scheduled Task. I had to move the initialization of %flag to be done before that very-first IF.

Related

Run a batch file from Task Scheduler is not working with a java command

Run a batch file from Task Scheduler is not working with a java command inside the .bat file. If I run the .bat file manually its working good.
Here is the simple .bat file I'm trying to schedule
set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_24;
set CMD= "%JAVA_HOME%\bin\java" -version
echo %CMD%
%CMD%
When you type batchfile.bat on the command line, you are telling cmd.exe to read the file and execute each line it finds in it. When you double-click on your batch file in explorer, it calls cmd.exe for you, after reading the file associations in the registry.
Task Manager is not so kind.
So for your task to work, schedule it like this (from memory, not on a Windows box right now) :
cmd /c "c:\full\path\to\your\batchfile.bat"
For extra robustness, you could make sure you batch file run from a known directory, like the one that it reside in, by adding this at the top:
pushd %~dp0
REM .... The original batch file goes here ....
popd
And finally you could disable CMD autorun entry by adding /d right after cmd like this:
cmd /d /c "c:\full\path\to\your\batchfile.bat"
If ixe013's suggestion doesnt work go to
'Actions'
'Edit' the task
'Start in (optional):' Put the path to the directory where the script is
So for the last one if you have 'C:\Users\Desktop\script.py' just put in 'C:\Users\Desktop\' in the 'Start in (optional):' field
What worked for me was running the task as "Users" ( computername\Users ). Once I did that, and "run with highest privileges" checked, it ran without a hitch.
Giving the full path of java.exe in the batch file fixed it for me. In a notepad, I typed the following line:
"C:\Program Files\Java\jdk1.8.0_40\bin\java.exe" -jar "C:\Users\usernameXXXX\Documents\NetBeansProjects\JavaApplication5\dist\JavaApplication5.jar"
Save this as a app1.bat file (C:\temp\app1.bat)
In the Actions tab of the task scheduler, give the path to the batch file, i.e, C:\temp\app1.bat
Also, be careful in the Conditions tab of task scheduler- make sure you uncheck "Start the task only if the computer is on AC power"
All other ways did not work for me, I followed this guide:
http://richardstk.com/2012/06/15/scheduled-task-to-run-a-batch-file/#comment-6873
In order to get the batch file to run, I had to set the "Program\script" box to contain just the name of the script (ie. script.bat) and set the the folder path of the script in the "Start in (optional)" box
I gave full permission to user Everyone from security tab from Properties of the folder in which batch file is. and it started working.
What a coworker discovered on something he had that wasn't working, and I have verified on the system I had that wasn't working is the following:
When the whole task is initially setup, you HAVE TO initially use the radio button "Run only when user is logged on". It will ask for your password for the change.
Now run the task.
Verify that whatever the batch was supposed to do, did happen.
And THEN change to the radio button BACK TO 'Run whether user is logged on or not."
This solved a problem for both of us that we had individually been working on for hours.
Side notes: both issues were also trying to elicit a 3rd party FTP app (WinSCP and WinFTP respectively) in each of our cases. Regular "inhouse" batch/tasks were having no issues.
I had the same problem, and to solve it, I put the next command line into the batch file:
cd "CURRENT_DIRECTORY"
where CURRENT_DIRECTORY is the directory where the batch file is located.
Example:
Suppose i have my batch file named test.bat located into c:\windows\system32\mytest
in my test.bat file, i introduce the next command line:
cd c:\windows\system32\mytest

Execute Batch Script From Environment Variable

I've set an system environment variable called find which points to a batch script. I did this so that in Win command prompt i could type %find% and it would execute my script. It works the only problem is it only works once, my script takes a parameter or requires user input (have tried both), and then it is as if the %find% is temporarily overwritten, and the %find% of course no longer works, until i reopen the command window. Basically it works once and that's it!
How can i make it work every time? i want to execute my script using the environment variable over and over again at will without reloading the command window.
Thanks.
I created a batch script with the following code:
#ECHO off
echo hello
and added a environmental variable called TEST that points to the script. I have no problem executing the script using the environmental variable multiple times.
Can you please provide some information or code of what your script does?
Remember that find is a MS-supplied utility.
Try using a different name. And show us your batch - even possibly describe what happens when it "no longer works." Games of 20-questions are tedious.
The problem is that the Batch script uses a variable with the same name, so after it run for the first time the variable value is overwritten and no longer works. To prevent this to happen, insert a setlocal command at beginning of the Batch file; this way, when the script ends all variables are reset to the values they had before the script run. This method also delete all new variables defined in the Batch script, so it keep the environment clean.
If your intention is to override the behavior of the existing find.exe utility, you could add the location of the script to the global path variable before your System32 folder (where find.exe is located). For example, let's say your script is C:\Scripts\find.bat. If your path variable is currently set to this:
%SystemRoot%\system32;%SystemRoot%
...then you would change it to this:
C:\Scripts;%SystemRoot%\system32;%SystemRoot%
Beware though... doing this could break other scripts that use the find command (if they don't use the absolute path to find.exe).
If you are just wanting an easy way to run your alternate find command, you could just give it a different name as the others have suggested, then add it to the end of the path or place it in the System32 folder. That would save you from having to type the percent signs at least.

how do i execute a statement in batch /powershell just once?

I want to know how to execute a set of statements or a command in a Windows Batch file or PowerShell script to be executed just once. Even if I run the script multiple times, that particular set of code or program should just run once.
If possible give an example for both Batch files and PowerShell.
In both cases you need to make changes that (a) persist beyond running the batch file or PowerShell script and (b) are visible when you start it the next time. What those changes are would depend on how cluttered you want to leave the system.
One option would be an environment variable. You can set those from batch files with setx or from PowerShell with [Environment]::SetEnvironmentVariable. You should also set them normally to have them in the current session, just to make sure that it can't be called from that session again, too.
if defined AlreadyRun (
echo This script ran already
goto :eof
)
...
setx AlreadyRun 1
set AlreadyRun 1
or
if (Test-Path Env:\AlreadyRun) {
Write-Host This script ran already
exit
}
...
[Environment]::SetEnvironmentVariable('AlreadyRun', '1', [EnvironmentVariableTarget]::User)
'1' > Env:\AlreadyRun
This approach has its drawbacks, though. For example, it won't prevent you from running the same script twice in different processes that both existed at the time the script ran first. This is because environment variables are populated on process start-up and thus even the system-wide change only applies to new processes, not to those already running.
Another option would be a file you check for existence. This has the benefit of working even under the scenario outlined above that fails with environment variables. On the other hand, a file might be accidentally deleted easier than an environment variable.
However, since I believe your batch file or PowerShell script should do something, i.e. have a side-effect, you should probably use exactly that as your criterion for abort. That is, if the side-effect is visible somehow. E.g. if you are changing some system setting or creating a bunch of output files, etc. you can just check if the change has already been made or whether the files are already there.
A probably very safe option is to delete or rename the batch file / PowerShell script at the end of its first run. Or at least change the extension to something that won't be executed easily.

Batch process all files in directory

Right now i have a batch job I wrote that calls another file and passes in the variables that executable needs to run (password and filename).
Ex:
> cd f:\test\utils
> admin import-xml -Dimport.file=f:\DB\file1.xml -Dadmin.db.password=test123
I wrote a job that does this, but found out that there would be multiple files.
The username and password never change but the filename differs for like 15 different xml files--with maybe more coming soon.
The files will always be located in the same folder. Instead of ending up with like 15-20 jobs (one for each file), can I write something that will process each file located in this directory. And either wait till one is completed before the next or I can add a 3 min sleep before it starts the next file.
pushd C:\test\utils
for %%F in (F:\DB\*.xml) do (
admin import-xml "-Dimport.file=%%~dpnxF" -Dadmin.db.password=test123
)
popd
The %%~dpnxF expands to d‎rive, p‎ath, base‎n‎ame and e‎x‎tension of the current file.
If you intend to set and use environment variables (%foo%) in that loop, read help set first before you get into trouble.
You can use the for command. Something like this in a batch file:
for %%f in (*.xml) do call myotherbatch.bat %%f
Assuming that the admin command you are running doesn't return until the job is finished, the above loop would process them sequentially.
If you run the command at the prompt (as opposed to in a batch file), only use a single %.
for file in f:\DB\*
do
admin import-xml -Dimport.file="$file" -Dadmin.db.password=test123
done

CMD: Bat to Exe Converter - Temp directory problem

i am using 'Bat to Exe Converter' to convert my batch files to exe format.
Now, i am running into some problems.
Whenever i convert something, and i set 'Working Directory' to 'Current Directory', and i start my exe in echo on mode, this is what i end up with to check if there is a specific file in the directory of my exe:
the actual command: if not exist "%~dp0\file.txt" goto :nofile
output: if not exist "C:\Users\MyUser\AppData\Local\Temp\4CBC\\file.txt" goto :nofile
Can anyone help me with this? I don't want it in the temp directory, i want it to be in the directory of my exe.
Thanks.
Without having Bat to Exe changed by the author, I think you have two options:
Remove the need for accessing %~dp0
Perhaps you can merge file.txt with the include option of Bat to Exe into the EXE file. If so, "file.txt" will automatically be unpacked in the current directory when running your compiled exe, and you can it access by %CD%\file.txt.
Get %~dp0 from outside and pass it to the exe as a command line parameter.
This can be done by a simple starter bat file that resides in the same directory as your compiled main batch file. This script schould contain the line
YourCompiled.Exe %~dp0% %%*
Your compiled exe then gets its directory from %1. So you cannot pack everything into one exe, but the main portion of it, perhaps that is sufficient for you.
Well, apparently your batch to exe converter simply packs the batch file and extracts it to a temporary directory prior to execution. Very simplistic, hard to get wrong (compared to actually understand the batch file) but it introduces errors such as the one you're describing.
Your best bet is probably to use another batch to exe converter; some of them are actually a little more sophisticated.
Generally, this is not a good idea. firstly, its prone to errors and instability of the converter on different cmd features. secondly, a determined hacker can still decode what you are doing with the batch. My suggestion, if you are so afraid of people looking into your batch,
1) let only the people who are authorized to use your batch to use it
2) give them the correct permissions.
OR, don't use batch at all
1) create a central interface such as a web interface, where all tasks to be done goes through that interface, like using an ATM machine where only buttons are allowed and all the available user options can be done by pushing buttons...etc..
2) authenticate your users through a central authentication system, eg Active Directory, or LDAP or a database.
This is an 2.5 yr old subject but there is an answer to this so I'm posting for anyone else that happens to find this in a search.
B2EC written by Fatih Kodak, has an option to "Submit current directory".
When this is used, you can reference %1 in your batch file to get the path of the EXE that was executed (instead of the path of the extracted BAT that is really being run).
Hovering over that option in the UI shows "Submit the current working directory as the last parameter". The "last parameter" in my use has always been %1 but you can test your code to be sure.
The latest version, 2.1.4 at time of writing, of Bat to Exe by Fatih Kodak creates an Environmental Variable at runtime that can be substituted in place of %~dp0 to reference the Exe's path. Therefore, you can simply replace %-dp0 with %b2eprogrampathname% in the original batch file.
You can use external folders with f2ko's batch to exe converter. Having
a separate folder for subroutines can neaten up a project folder.
To call mysubroutine that is located in mysubroutinesfolder\mysubroutine,
...
pushd mysubroutinesfolder
call mysubroutine
popd
...
The call can be made a one liner:
call xqt mysubroutine
where xqt.cmd is a program that does the call for you:
pushd mysubroutinesfolder
call %*
popd
exit /b
(the %* means "all of the arguments").
In this way your batch programs run as batch, and UNMODIFIED they will
compile with the bat to exe converter, creating a completely folder independent executable. Select "temporary directory",
and include all of the subroutines/executables in your mysubroutines folder
by "selecting them all" with your cursor as usual, then hit "copy".
Be sure to include the xqt.cmd program too; place it "outside" of your mysubroutines folder. Make sure that is is accessible by your main program. Remember to select x64 if you
are runnning on a x64 machine, or the executable will not find SYSTEM32
files. You can find f2k0's batch to exe converter at:
http://www.f2ko.de/programs.php?pid=b2e
Try this development environment for batch scripts, Batch Compiler . It has everything you need to develop a batch program.And compile into stable stand alone executable (Exe).
Friendly user interface.
Debugger, Check your code for syntax errors.
Powerful, versatile compiler.
Allows mouse input in batch files.
Use Windows Common Dialog Boxes.(BrowseFiles,BrowseFolders)
Draw graphics in batch files.
Reverse engineering proof encryption of source code.
Include Company name, Copyright info and Version info.
Make invisible(silent) executables.
Executables with administrator privileges.
Run & debug your script while editing.
Embed resources with executable.(music,images,files)
Advance Commands (BrowseFiles,LaunchSilent,MouseCMD)
Stand-alone executables.No dependencies needed.
Executables are woking on almost all windows operating systems.(98 to 10)
Quick download : http://bc.gotek.info/files/BatchCompiler159.zip
Cheers!
%cd% will give you the current directory:
if not exist "%CD%\file.txt" goto :nofile
Use %CD% instead of %~dp0.
EDIT:
B2EC is not a real converter. Creation location of equipped .cmd file was chosen to be %TEMP% and this is a good choice. Application just lacks 3rd option for working directory of the script - .exe file directory. I advise you to mail the author about adding this one.
Different paths for .exe and created .cmd lead to information loss, i.e. we are unable to know .exe directory and current directory at the same time without providing additional information to the script (e.g. using environment variable or passing it as first/last argument to the script). This script would need to handle it and we would end writing cmd scripts tailored for this converter, which is bad.
%~dp0 - script directory (%TEMP%/.../) - practically useless
%cd% - working directory (as set up in the converter) - currently there are only 2 options: current directory (working directory of .exe) and temporary directory (actually equal to %~dp0, but without trailing backslash)
I think it can be solved by patching cmd.exe instance in memory to change the script path, but that's B2EC developer's duty.
Side note: Normal executable files can be easily executed with specified 0th argument by providing appriopriate lpApplicationName and lpCommandLine to CreateProcess function. Command files are executed via cmd.exe, so 0th argument cannot be set this way.

Resources