Execute Batch Script From Environment Variable - windows

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.

Related

Set environment variable in nested batch file

I am trying to factor out a piece of a batch file that sets an environment variable to another batch file. This piece is somewhat involved and I would rather not repeat it in multiple batch files. I won't over-complicate this post with the actual code I'm trying to run in the nested batch file, but will provide a simple example that shows what I'm trying to do and reproduces the problem.
Batch1.cmd
cmd.exe /c setvar.cmd abc def
set abc
setvar.cmd
set var=%1
set val=%2
set %var%=%val%
The error returned for "set abc" in Batch1.cmd is this:
Environment variable abc not defined
I imagine cmd.exe starts up a new environment, because on return to Batch1.cmd, the variable does not exist.
Is there a way I can nest a batch file and keep the environment it creates?
The environment block is not shared between processes. As you are starting a new cmd instance a separate environment block is created, changed and destroyed before returning the control to the current batch file, that will not see any change as it was done in a different process.
Use call setvar.cmd abc def to start the nested batch file in the current process.
Use the setx <var> <val> command to set an environment variable more persistently. For example:
setx WEBCAM_ADDR 192.168.0.101
(Note: There is NO equals sign (=) as with the regular set command)
I just went through this issue, trying to run batch files from windows. This is better than having to write, say, a configuration file somewhere...

prevent Windows .bat file from quiting

I have a very simple Windows .BAT file:
set PATH=c:\xxx;%PATH%
call foo.pl
set VAR=true
I thought "call" will start a new batch process, without affecting the current one. However, the batch file exited immediately after the foo.pl finished executing. The set VAR=true has never been called.
Is there a way to fix it?
foo.pl is not a batch file, it is a Perl script.
So you need to use
path c:\xxx;%PATH%
"Path to\Folder With\perl.exe" "foo.pl"
rem Additional batch code executed after Perl script execution finished.
In other words you have to run the console application perl.exe best with full path, or with just perl.exe if program files folder of Perl is not the same on all computers on which this batch file is used and hopefully PATH contains also the directory containing perl.exe.
If you specify on a command line or in a batch file just foo.pl, Windows looks in Windows registry which application is associated with .pl for action Open. If there is such a file association, Windows runs this application in a separate process like when using command start.
So using call foo.pl is like using start foo.pl.
PATH is not only an environment variable, but also an interal command written for changing the value of environment variable PATH at any time within a batch file. This is the reason why I removed set from first line. It is better to use internal command path for modifying environment variable PATH.

Task Scheduled not running batch file

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.

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.

Order in which command prompt executes files with the same name (a.bat vs a.cmd vs a.exe)

What is the order in which the Windows command prompt executes files with the same name, but different extensions?
For example, I have a bunch of executable files: something.cmd, something.bat and something.exe. Which of these would be executed when I typed something into a command prompt (given they were on the path, etc.)? If that file did not exist which one would then be executed?
Is there a reference that describes this?
Okay, I did some quick experimentation based on some other searches I had going.
The gist is that the order of the commands is dependent on the order the extensions are stored in the PATHEXT environment variable. So initially I had:
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.RB;.RBW
and for the example above the order in which it would run it was:
something.exe
something.bat
something.cmd
Changing the order which they were defined in the PATHEXT environment variable did indeed change the order in which they were executed.

Resources