Execute a batch file before executing in a shortcut (.lnk) - windows

I have multiple versions of a program called Siemens NX. NX uses environmental variables for configuration. I need NX 10.0 to use a different set of environmental variables than my NX 7.5 which uses the system environmental variables. Therefore, I have written a batch file that setups the environmental variables that I need. However, There is a lot of different programs that go with NX 10.0. I don't want to have to create a batch file for each program. Instead, I just want to ammend the shortcuts (.lnk) to execute a batch file before starting. For instance, this is easily done by
C:\Siemens\NX10\UGII\setup_NX10_environment.bat && C:\Siemens\NX10\UGII\ugraf.exe -nx
However, the command window is left open. How can I call the batch script and it closes and then calls my program?

Supply program with parameters to your batch script as follows
C:\Siemens\NX10\UGII\setup_NX10_environment.bat "C:\Siemens\NX10\UGII\ugraf.exe" -nx
and improve that batch as follows:
rem all the original setup_NX10_environment.bat stuff here
%*
exit
or
rem all the original setup_NX10_environment.bat stuff here
call %*
exit
or
rem all the original setup_NX10_environment.bat stuff here
start "" %*
exit

The console window may remain open if you call the executable like this:
executable.exe
However, prepending start to the executable will detach it from the console.
Thus the console will not remain open if you call the executable like this:
start executable.exe
In conclusion, rewrite your command as follows:
C:\Siemens\NX10\UGII\setup_NX10_environment.bat && start C:\Siemens\NX10\UGII\ugraf.exe -nx

Related

octave-gui invoked by bat script does not work unless you run octave(-gui) before (or "run octave-cli.exe with qt")

I want to run octave-gui (Octave 5.1 installed with installer and "C:\Octave\mingw64\bin" is in path variable) scripts run by Windows Task Scheduler. I have to run octave-gui since I want to use the qt toolkit for plotting that octave (without gui) does not support. Therefore I normally use simple bat files like "octave-gui --no-gui c:\path\myfile.m".
But the problem is that I cannot run this bat file by clicking in the Windows Explorer or running from command line. Even the most simple bat file with the content "octave-gui --no-gui" gives me the following error:
But the funny part is that I can make it work somehow:
open command line
run "octave" or "octave-gui" and close/quit it
then I can the bat file from the command line
But this could not be the solution, could it? This only works in the (interactive) command line. How does it work in the Task Scheduler?
So, do you have a solution to run either batch files using octave-gui or octave with qt toolkit.
Here is the workaround with "where" as asked by Gerhard:
The command octave is technically incorrect.
It works only from your Command Prompt window because its extension .bat is listed within the values assigned to an unmodified environment variable %PATHEXT%. It also assumes that there are no other files named octave.com or octave.exe, anywhere within the any of the directories listed under your environment variable %PATH%. Additionally it also assumes that there is not an executable file named octave with any extension listed under %PATHEXT% in the current directory when invoked.
You should, for safety, use octave.bat instead.
octave.bat
Octave.bat will parse any input arguments, set up the required environment, and then run either start octave-gui.exe --gui %* or octave-cli.exe %* if it detected --no-gui as one of the input arguments.
Additionally when running a batch file from another, (in this case start_my_octave_script.bat), you should Call it if you're wanting control to return to it afterwards, which will almost certainly be the case.
call octave.bat <command line options>
If you're satisfied that your %PATHEXT% environment variable is unmodified or at least holds the default values, you can omit the .batextension, but please bear in mind the previous advice.
call octave <command line options>
I made a workaround thanks to the hints made by Compo. It seems to me that a solution must be done in the "octave.bat" and so I did. I made a copy and named it "octave-gui-nogui-withqt.bat" and removed all the gui checking stuff and only run "octave-gui.exe --no-gui" (scroll down):
:; # if running from bash, recall using cmd.exe
:; cmd.exe //c "$0" "$#"; exit $?
#echo off
Rem Find Octave's install directory through cmd.exe variables.
Rem This batch file should reside in Octaves installation bin dir!
Rem
Rem This trick finds the location where the batch file resides.
Rem Note: the result ends with a backslash.
set OCT_HOME=%~dp0\.\..\
Rem Convert to 8.3 format so we don't have to worry about spaces.
for %%I in ("%OCT_HOME%") do set OCT_HOME=%%~sI
Rem Set up PATH. Make sure the octave bin dir comes first.
set PATH=%OCT_HOME%qt5\bin;%OCT_HOME%bin;%PATH%
Rem Set up any environment vars we may need.
set TERM=cygwin
set GNUTERM=wxt
set GS=gs.exe
Rem QT_PLUGIN_PATH must be set to avoid segfault (bug #53419).
IF EXIST "%OCT_HOME%\qt5\bin\" (
set QT_PLUGIN_PATH=%OCT_HOME%\qt5\plugins
) ELSE (
set QT_PLUGIN_PATH=%OCT_HOME%\plugins
)
Rem set home if not already set
if "%HOME%"=="" set HOME=%USERPROFILE%
if "%HOME%"=="" set HOME=%HOMEDRIVE%%HOMEPATH%
Rem set HOME to 8.3 format
for %%I in ("%HOME%") do set HOME=%%~sI
Rem Start Octave (this detaches and immediately returns).
Rem make this call in order to have qt on the cli
octave-gui.exe --no-gui %*
Is this the most elegant one? I guess that upstream Octave should allow a new option like "--no-gui-but-use-qt" or similar. What do you think?
It still confuses me that "octave-cli.exe" and "octave-gui.exe" have more differences besides the visible gui.

How to maintain environment variables of a bat file before executing another program in a bat file?

A way to run multiple programs in a bat file.
Objective
Distribute a software with GDAL as a dependency.
To do that I have downloaded gdal binaries from GIS Internals. The downloaded data has a .bat file to set environment variables. It uses set command to set the environment variables.
As per my limited knowledge in windows bash scripting, I understand that the environment variables set by set are limited to current command prompt itself and are reset when a new command prompt is launched.
Also, is it true that a calling a batch file from a batch file launches new command prompt which when closes doesn't affect the next command called in the parent script.
There is another issue here - will the environment variables affect the process created (such as calling gdal_translate) by a Java program? If it doesn't, then there is no point in setting local environment variable.
Final Requirement:
How to use the environment variables set in another batch file (called from a batch file) in the next line of the parent batch file, without using setx?
If you use the CALL command to run the batch file as specified in the accepted answer on the question you linked to, then the environment variables will pass up to the parent batch file.
There are three times where this is not true:
When using SETX neither the parent nor child batch file will get the environment variables.
When using SETLOCAL and ENDLOCAL inside the child batch file the parent batch file will not get the environment variables.
When running the child batch file using start or cmd.exe /c.
So long as you run your Java application in the same environment (i.e. the same batch file), it will pick up the same environment variables. You can verify this with an application like Process Explorer.
Running set _kjhgkjshdgkjhdfg=TEST before running a .jar file resulted in the screenshot below using any of:
javaw -jar jarfile.jar
cmd /c javaw -jar jarfile.jar
start cmd /c javaw -jar jarfile.jar

Why is an error message output instead of starting an executable in subdirectory of batch file directory?

An error message is output when I try to start "launcher.exe" located in anylocation\ffa\ with this command:
start \ffa\launcher.exe
Batch script should have access to file because stored on disk like this:
ANYLOCATION/myprogram.bat
ANYLOCATION/ffa/launcher.exe
If I type
start /ffa/launcher.exe
output is: invalid switch
But if I type
start \ffa\launcher.exe
output is system cannot find file
Which mistake to I made on starting launcher.exe?
%~dp0
is your batch file directory. So
%~dp0\ffa\launcher.exe
There is no need to use start.
Starting a Program
See start /? and call /? for help on all three ways.
Specify a program name
c:\windows\notepad.exe
In a batch file the batch will wait for the program to exit. When
typed the command prompt does not wait for graphical
programs to exit.
If the program is a batch file control is transferred and the rest of the calling batch file is not executed.
Use Start command
start "" c:\windows\notepad.exe
Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start.
Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try
start shell:cache
Use Call command
Call is used to start batch files and wait for them to exit and continue the current batch file.

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.

How to run VBScript from command line without Cscript/Wscript

I am a beginner in VBScript. I googled it & got to know that we can run VBScript from command line by executing below command:
For Example my vbscript name is Converter.vbs & it's present in folder D:\VBS.
I can run it through following methods:
CScript "D:\VBS\Converter.vbs"
OR
WScript "D:\VBS\Converter.vbs"
Now I would like to execute above VBScript without Cscript or Wscript command by simply typing the name of VBscript name i.e. Converter.
I DON'T WANT TO SPECIFY THE FULL PATH OF VBSCRIPT EVERYTIME.
Can anyone please guide me on how to do that ?
I'll break this down in to several distinct parts, as each part can be done individually. (I see the similar answer, but I'm going to give a more detailed explanation here..)
First part, in order to avoid typing "CScript" (or "WScript"), you need to tell Windows how to launch a * .vbs script file. In My Windows 8 (I cannot be sure all these commands work exactly as shown here in older Windows, but the process is the same, even if you have to change the commands slightly), launch a console window (aka "command prompt", or aka [incorrectly] "dos prompt") and type "assoc .vbs". That should result in a response such as:
C:\Windows\System32>assoc .vbs
.vbs=VBSFile
Using that, you then type "ftype VBSFile", which should result in a response of:
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
-OR-
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\CScript.exe" "%1" %*
If these two are already defined as above, your Windows' is already set up to know how to launch a * .vbs file. (BTW, WScript and CScript are the same program, using different names. WScript launches the script as if it were a GUI program, and CScript launches it as if it were a command line program. See other sites and/or documentation for these details and caveats.)
If either of the commands did not respond as above (or similar responses, if the file type reported by assoc and/or the command executed as reported by ftype have different names or locations), you can enter them yourself:
C:\Windows\System32>assoc .vbs=VBSFile
-and/or-
C:\Windows\System32>ftype vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
You can also type "help assoc" or "help ftype" for additional information on these commands, which are often handy when you want to automatically run certain programs by simply typing a filename with a specific extension. (Be careful though, as some file extensions are specially set up by Windows or programs you may have installed so they operate correctly. Always check the currently assigned values reported by assoc/ftype and save them in a text file somewhere in case you have to restore them.)
Second part, avoiding typing the file extension when typing the command from the console window.. Understanding how Windows (and the CMD.EXE program) finds commands you type is useful for this (and the next) part. When you type a command, let's use "querty" as an example command, the system will first try to find the command in it's internal list of commands (via settings in the Windows' registry for the system itself, or programmed in in the case of CMD.EXE). Since there is no such command, it will then try to find the command in the current %PATH% environment variable. In older versions of DOS/Windows, CMD.EXE (and/or COMMAND.COM) would automatically add the file extensions ".bat", ".exe", ".com" and possibly ".cmd" to the command name you typed, unless you explicitly typed an extension (such as "querty.bat" to avoid running "querty.exe" by mistake). In more modern Windows, it will try the extensions listed in the %PATHEXT% environment variable. So all you have to do is add .vbs to %PATHEXT%. For example, here's my %PATHEXT%:
C:\Windows\System32>set pathext
PATHEXT=.PLX;.PLW;.PL;.BAT;.CMD;.VBS;.COM;.EXE;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY
Notice that the extensions MUST include the ".", are separated by ";", and that .VBS is listed AFTER .CMD, but BEFORE .COM. This means that if the command processor (CMD.EXE) finds more than one match, it'll use the first one listed. That is, if I have query.cmd, querty.vbs and querty.com, it'll use querty.cmd.
Now, if you want to do this all the time without having to keep setting %PATHEXT%, you'll have to modify the system environment. Typing it in a console window only changes it for that console window session. I'll leave this process as an exercise for the reader. :-P
Third part, getting the script to run without always typing the full path. This part, in relation to the second part, has been around since the days of DOS. Simply make sure the file is in one of the directories (folders, for you Windows' folk!) listed in the %PATH% environment variable. My suggestion is to make your own directory to store various files and programs you create or use often from the console window/command prompt (that is, don't worry about doing this for programs you run from the start menu or any other method.. only the console window. Don't mess with programs that are installed by Windows or an automated installer unless you know what you're doing).
Personally, I always create a "C:\sys\bat" directory for batch files, a "C:\sys\bin" directory for * .exe and * .com files (for example, if you download something like "md5sum", a MD5 checksum utility), a "C:\sys\wsh" directory for VBScripts (and JScripts, named "wsh" because both are executed using the "Windows Scripting Host", or "wsh" program), and so on. I then add these to my system %PATH% variable (Control Panel -> Advanced System Settings -> Advanced tab -> Environment Variables button), so Windows can always find them when I type them.
Combining all three parts will result in configuring your Windows system so that anywhere you can type in a command-line command, you can launch your VBScript by just typing it's base file name. You can do the same for just about any file type/extension; As you probably saw in my %PATHEXT% output, my system is set up to run Perl scripts (.PLX;.PLW;.PL) and Python (.PY) scripts as well. (I also put "C:\sys\bat;C:\sys\scripts;C:\sys\wsh;C:\sys\bin" at the front of my %PATH%, and put various batch files, script files, et cetera, in these directories, so Windows can always find them. This is also handy if you want to "override" some commands: Putting the * .bat files first in the path makes the system find them before the * .exe files, for example, and then the * .bat file can launch the actual program by giving the full path to the actual *. exe file. Check out the various sites on "batch file programming" for details and other examples of the power of the command line.. It isn't dead yet!)
One final note: DO check out some of the other sites for various warnings and caveats. This question posed a script named "converter.vbs", which is dangerously close to the command "convert.exe", which is a Windows program to convert your hard drive from a FAT file system to a NTFS file system.. Something that can clobber your hard drive if you make a typing mistake!
On the other hand, using the above techniques you can insulate yourself from such mistakes, too. Using CONVERT.EXE as an example.. Rename it to something like "REAL_CONVERT.EXE", then create a file like "C:\sys\bat\convert.bat" which contains:
#ECHO OFF
ECHO !DANGER! !DANGER! !DANGER! !DANGER, WILL ROBINSON!
ECHO This command will convert your hard drive to NTFS! DO YOU REALLY WANT TO DO THIS?!
ECHO PRESS CONTROL-C TO ABORT, otherwise..
REM "PAUSE" will pause the batch file with the message "Press any key to continue...",
REM and also allow the user to press CONTROL-C which will prompt the user to abort or
REM continue running the batch file.
PAUSE
ECHO Okay, if you're really determined to do this, type this command:
ECHO. %SystemRoot%\SYSTEM32\REAL_CONVERT.EXE
ECHO to run the real CONVERT.EXE program. Have a nice day!
You can also use CHOICE.EXE in modern Windows to make the user type "y" or "n" if they really want to continue, and so on.. Again, the power of batch (and scripting) files!
Here's some links to some good resources on how to use all this power:
http://ss64.com/
http://www.computerhope.com/batch.htm
http://commandwindows.com/batch.htm
http://www.robvanderwoude.com/batchfiles.php
Most of these sites are geared towards batch files, but most of the information in them applies to running any kind of batch (* .bat) file, command (* .cmd) file, and scripting (* .vbs, * .js, * .pl, * .py, and so on) files.
When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by
assoc | grep -i vbs
.vbs=VBSFile
ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*
to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.
As
cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]
Options:
//B Batch mode: Suppresses script errors and prompts from displaying
//D Enable Active Debugging
//E:engine Use engine for executing script
//H:CScript Changes the default script host to CScript.exe
//H:WScript Changes the default script host to WScript.exe (default)
//I Interactive mode (default, opposite of //B)
//Job:xxxx Execute a WSF job
//Logo Display logo (default)
//Nologo Prevent logo display: No banner will be shown at execution time
//S Save current command line options for this user
//T:nn Time out in seconds: Maximum time a script is permitted to run
//X Execute script in debugger
//U Use Unicode for redirected I/O from the console
shows, you can use //E and //S to permanently switch your default host to cscript.exe.
If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable
set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1
contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.
Update wrt comment:
If you 'don't want to specify the full path of my vbscript everytime' you may:
put your CONVERTER.VBS in a folder that is included in the PATH environment variable; the shell will then search all pathes - if necessary taking the PATHEXT and the ftype/assoc info into account - for a matching 'executable'.
put a CONVERTER.BAT/.CMD into a path directory that contains a line like cscript p:\ath\to\CONVERTER.VBS
In both cases I would type out the extension to avoid (nasty) surprises.
I am wondering why you cannot put this in a batch file. Example:
cd D:\VBS\
WSCript Converter.vbs
Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.
Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.
Check the answer -> Here
And here is an example:
Converter.bat
::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &#echo off
rem^ &call :'sub
rem^ &exit /b
:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b
'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester
You may follow the following steps:
Open your CMD(Command Prompt)
Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:
Type 'CD VBS' and hit Enter. Example: D:>CD VBS
Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs

Resources