execute an exe without knowing full path - batch-file

I need to start an application by the name of Acad.exe without knowing its full path. this path is namly decide upon instalation by the person installing the app.
how can i achive this?

It is common for applications to store their install location in the registry, so the preferred way of finding them would be to look up the appropriate place in the registry. That way, you won't accidentally start a different program with the same file name.
Assuming acad.exe is AutoCAD, this page gives the locations you have to look up.

Try this in any language that has an interface to the OLE2 layer:
CreateDispatch("Autocad.Application")
In C++:
::CoInitializeEx(NULL);
::CreateDispatch("AutoCAD.Application");
With a batch script:
Save the following under the name `start_autocad.vbs
set objShell=CreateObject("Autocad.Application")
objShell.Visible = TRUE
run cscript start_autocad.vbs.

If this acad.exe installation follows the Windows convention, the installation process creates a special key in the registry :
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
If acad.exe is defined there with required parameters then it's possible to start it from a batch file with this simple command :
START acad.exe
No need to specify the complete path, Windows will get it from the corresponding AppPath entry.

Assuming it is on the C: drive, you could do:
#echo off
c:
cd \
for /f "delims=" %%a in ('dir /s /b acad.exe') do set exeLcn=%%a
start %exeLcn%

Instead of inventing your own method, you just might reproduce the behavior of CMD.EXE, looking for ACAD.EXE in the %PATH%.
try this as an example to get you started...
:inpath
echo %~$PATH:1
echo %~dp$PATH:1
goto :eof
invoke it this way
call :inpath acad.exe

Related

Is there an API which exposes the paths searched by the start command?

What paths are searched by start? Is this path list queryable via WMI, the registry, WSH shell folder constants, .NET methods, or any other Windows API?
In a cmd console, the start command is sort of magic. Say your default web browser is Firefox. You also have Chrome and Opera installed, but they are neither set as default, nor associated with any file types, nor in your %PATH%. Considering the following example:
start "" opera https://stackoverflow.com
... why does that work?
The reason this matters is that, for all the start command's strengths, it is still perilous to retrieve an application's PID or window handle when that application was launched with start. In a cmd environment I'd prefer to use wmic process call create in a for /F loop to capture the PID. So is there a way I can teach wmic process call create to launch "opera" or "iexplore" or "outlook" or "winword" or other applications as start can without fully qualifying the drive:\\path\\to\\executable?
I thought I was on to a solution by scanning HKLM\Software\Clients recursively for shell\open\command, then adding each referenced location temporarily to %PATH%:
rem // temp add installed clients to %PATH% to make "call :display" behave like "start"
setlocal enabledelayedexpansion
for %%a in (HKLM HKCU) do for /f "tokens=2*" %%I in (
'REG QUERY %%a\Software\Clients /s /f command /k /ve ^| find "(Default)"'
) do if "%%~I"=="REG_EXPAND_SZ" (
if /i "%%~xJ"==".exe" (
if "!PATH:%%~J\..=!"=="!PATH!" path !PATH!;%%~J\..
) else for %%# in (%%J) do if /i "%%~x#"==".exe" (
if "!PATH:%%~#\..=!"=="!PATH!" path !PATH!;%%~#\..
)
) else (
if /i "%%~xJ"==".exe" (
if "!PATH:%%~dpJ=!"=="!PATH!" path !PATH!;%%~dpJ
) else (
for %%# in (%%J) do if /i "%%~x#"==".exe" (
if "!PATH:%%~dp#=!"=="!PATH!" path !PATH!;%%~dp#
)
)
)
endlocal & path %PATH%
That works reasonably well, but it still falls short of what start can access. For example:
start "" wordpad
works, whereas
wmic process call create "wordpad.exe"
fails.
I remember a discussion about this very topic either on DosTips.com or here on SO but I cannot find it. Hopefully somebody does so we can mark this question as a duplicate.
We know that the batch files will search the current directory and then the path variable to find an executable. The START command also searches the following Registry path
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
So you have a few options to find the executable.
You can use the WHERE command which searches the current directory and the directories in the PATH variable.
where notepad.exe
You can also just search the path variable with a FOR command.
for %%I in (notepad.exe) do echo %%~$PATH:I
And of course you can search the registry path as I mentioned above by doing a REG QUERY.
Edit2
This may be of interest regards to what you are doing (as opposed to why something works the way it does).
From a previous answer
Can I create shorthand names for use inside cmd?
See Doskey /?.
You could do this doskey cddesk=cd "%userprofile%\desktop"
Then type cddesk.
By putting all your macros in a batch file you can autoload. Of course
you could do this with batchfiles too.
From Technical Reference to the Windows 2000 Registry, Microsoft,
2000.
AutoRun HKCU\Software\Microsoft\Command Processor
Data type Range Default value
REG_SZ list of commands There is no default value for this entry.
Description
Contains commands which are executed each time you start Cmd.exe.
Also see this batchfile https://pastebin.com/A2qLw8r3 that list
special names.
In a command prompt start shell:desktop
Or in Start - Run (Winkey + R) just shell:desktop
Edit
I'll just add some caveats here.
This is about opening executables using Start command. A massive amount of rules apply to non executable files.
Not using Start CMD pre-processes the command line and sends a FQFN to CreateProcess - so it's CMD that searches the path not CreateProcess.
https://learn.microsoft.com/en-us/windows/desktop/shell/launch is the documentation for ShellExecute. Everything ends up calling CreateProcess https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createprocessw. Plus CMD preprocessing is detailed here https://books.google.com.au/books/about/Windows_NT_Shell_Scripting.html?id=jrdQAAAAMAAJ&redir_esc=y. Also start /? provides documentation for all three ways to start files. A summary is here Command to run a .bat file
Some fun facts. CMD if it can't recognise a file extension will attempt to execute it. ShellExecute will content sniff unknown files https://learn.microsoft.com/en-us/windows/desktop/com/filetype-key.
quote from rojo: Thanks for the link dump. I'm struggling to understand how ShellExecute can save me from having to fully qualify path names though. That was my primary question. "To use ShellExecute or ShellExecuteEx, your application must specify the file or folder object that is to be acted on, and a verb that specifies the operation." It's the "specify the file or folder object" part that I'm asking about.
It uses the 6 steps under CreateProcess and if that turns up nothing it uses App Paths. If a verb is not specified the default verb is used (usually Open). See my answer here How do i automate the simulation of right clicking a file and selecting the first option using vbscript.
So it an intersection of 4 technologies. Compatibility with MSDos, changes made by IBM for OS/2 and updated by Microsoft for Windows 2000, the standard windows way of starting programs CreateProcess, and with Windows 95 we got shell functions which are based on OLE
quote from rojo: Snap! You're right! In PowerShell I was able to create a System.Diagnostics.Process object, set $ps.StartInfo.UseShellExecute = $true, and then start "wordpad" without any file extension or fully qualified path. Setting the .UseShellExecute property to $false caused the execution to fail. How interesting!

Batch File - Attrib +r %Var1%

I have a undoubtedly silly problem. I need to change the attribute of a file to read only. I know to use...
atrrib +r c:\somefile.txt
And it works. However in my program I want to use a variable in place of the path to be built up beforehand. Now if I write...
set File=c:\somefile.txt
attrib +r %File%
Then I get an error saying 'attrib' is not recognized as an internal or external command etc.
However if I echo %File% beforehand then I know the path to the file is correct and being read properly.
What is my error? Thanks a lot!!!
Edit:
set File=Main.xaml
set Folder=C:\Users\yef03111\Desktop\His0164\WINDOW\ALS026-01~EDF
set Path=%Folder%\%File%
echo %Path%
However if I change the echo to attrib +r and nothing else...
attrib +r %Path%
I get the 'attrib' not recognized error. This is the current example that is not working. Hope you can spot something from it!
The problem is that you are setting an environment variable called PATH. This is overwriting the system PATH variable which contains the location of the executable files such as attrib. The way it works is that in order to find a program to run, the OS looks up the PATH variable and searches in the folders listed there for executable files with the name of the program you are trying to run. When you change the PATH variable, the OS can no longer find the attrib command.
Change the name of your variable from path to filepath and it will work.
Path is a system variable that tells CMD, Explorer, and CreateProcess where to look for commands.
As you are trashing the system variable CMD no longer looks in system32 for commands like attrib.
set Path=%Folder%\%File%
As a general rule avoid likely names used by the system in naming your own things. A lot of people will do MyFile or ProgPath.
Also commands like attrib will always be found if the current directory is System32. The current directory is always searched first for commands (programs). I suspect RunAs is setting the current directory to System32.
I have tested your script using Cmd on windows 7. Works a treat, so I cant recreate what you are seeing.
I did quite a lot of batch scripting at one point, and I used to get random errors using standard windows notepad. Tell tail signs of issues in the script were whitespace characters. If you are using notepad, switch to using notepad++ to write this and see if you still get errors.

windows for loop statement is failing in jenkins

I am trying to copy a set of zip files through jenkins build. The same command works in windows cmd line but fails in jenkins build. The below is the command I am trying to execute
for /r %i in (./*.zip) do cp "%i" c:\temp
any help is appreciated.
"fails" how?
In all probability, you mean "fails to copy".
It's likely that you are using *nix replacement utilities, so you need to either ensure that cp.exe is on your path or use the windows utility copy, not cp.
Ah! the error is a syntax failure. Had you edited-in that extra information, even added such minor matters as the precise error-message, it would be easier to locate and advise.
In all probability, you need to use
for /r %%i in (./*.zip) do copy "%%i" c:\temp
but this is a guess in the absence of a complee error report.

How to set a PATH to a batch file in windows

In windows, I have two .bat files, say dir_a/a.bat, and dir_b/b.bat.
What I want is that after executing a.bat, I will be able to call b.bat. My approach now is to set a PATH to dir_b, so in a terminal that executed a.bat, I can just call b.bat and will be able to execute b.bat. Yet putting "set PATH=dir_b;%PATH%" in a.bat is not working. What did I do wrong?
For the case that you're dealing with a relative path:
You might notice that:
set path=%path%;"\..\..\..\vc98\bin\"
will ^^ NOT work ^^ !
So do it like this:
pushd "..\..\..\vc98\bin\"
path %cd%; %path%
popd
...and of course a
set path=%path%;%cd%
between the pushd and popd will also do the trick
Well for also have a look here:
https://stackoverflow.com/a/6595206/3135511
...
call :setAbsPath ABS_PATH ..\
...
^-To see to do it via the self made subfunction 'setAbsPath'
-> or instead of call you may also use For - details in the other thread
And just a small side note for those who might also like to run Microsoft Visual C++ 6.0(anno 1998) > without install it...
... and wonder where's that f*** 'standard' include ?!
There are about 17 file in \vc98\include\ that have been manually chopped 8 + 3 chars. Like:
algrithm -> algorithm
strstrem -> strstream
xception -> exception
So be aware and creative about that !
You must include the absolute path to b.bat file; for example:
set PATH=C:\User A\Folder X\dir_b;%PATH%
I suspect that you have a SETLOCAL in a.bat. ANY environment changes made after a SETLOCAL are backed out when the matching ENDLOCAL (or EOF in the same context) is reached.
Depending on how you are terminating a.bat, you'd need something in the order of ENDLOCAL&set "Path=dir_b;%PATH%"&GOTO :EOF which will prepend dir_b to your existing path as you appear to exepect for the duration of that particular CMD session.
Don't use PATH because that conflicts with the Windows Path. Instead you could add the following:
pushd path_to_your_dir_b
Then add popd in an appropriate place

Prevent overwriting a file using cmd if exist

I am currently writing a .bat batch file that executes an installation file. Before it runs the installation file I check to see if the directory exists to avoid re-installing the application.
I do this by using a If Not Exist filename statement. If the installed file doesn't exist, I then execute the installation file.
For some reason, when I test it with the application where it has been installed already, it is still trying to reinstall the application over it.
Here is a snippet of my code:
cd "C:\Documents and Settings\John\Start Menu\Programs\"
pause
If NOT exist "Software Folder"\ (
start \\filer\repo\lab\"software"\"myapp"\setup.exe
pause
)
Where SoftwareFolder is a subdirectory of "C:\Documents and Settings\John\Start Menu\Programs\". I am checking to see if it exists in my Programs folder.
I know nothing is wrong with my start command. I have a feeling something is wrong with my beginning CD command or one of its parameters.
Thanks a lot, guys!
Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:
If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"
I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...
CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"
two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult.
also...
start \\filer\repo\lab\"software"\"myapp"\setup.exe
the start code here, can be set up like that, but the correct syntax is
start "\\filter\repo\lab\software\myapp\" setup.exe
This will run: setup.exe, located in: \filter\repo\lab...etc.\
As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.
I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (
The correct version, with the space before the bracket, would be
If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
start "\\filer\repo\lab\software\myapp\setup.exe"
pause
)

Resources