Can a Windows batch file determine its "invoked" filename when invoked with shortcut? - windows

Can a Windows batch file determine its invoked filename when invoked through a shortcut?
For example, I create real.bat, and create its shortcut named phony.bat (.lnk?)
And invoke phony by double-click on it.
Can this batch file detect the name phony.bat instead of real.bat?
Of course I can just copy it to another name, but when I edit one of them, I have to manually sync the content to all files.
The question is related to Can a Windows batch file determine its own file name?, but different.

As in your you mentioned that you've created the shortcut I assume you can create the with any properties you want.
So right click on your lnk file and change the the target line to:
C:\Windows\System32\cmd.exe /c "set "lnk_call=1"&"C:\PATH\TO\your.bat" "
This will change the icon of the link so to set back to batch file cog click on change icon and find the bat file icon in :
%SystemRoot%\System32\SHELL32.dll
Finally in your bat put this line:
if defined lnk_call echo triggered from lnk file
the lnk_call now can be used to determine if your file is called from double clicking on a .lnk file. I don't think it is possible to detect this from a shortcut that anyone else created.

Oh yeah, I found hardlink useful in this case:
mklink /h <link-name> <source-file>
I can create many hardlinks with different name, and they all points to the same file, so I can freely edit any one of them without manually sync their content.

Related

Running a selfwritten ruby program outside of an IDE

I was wondering if it was possible to run a selfwritten ruby program just like any other program by double-clicking an icon of some sort.
And if it's possible, how do I do it?
I wrote a little program for a friend but I don't want him to have to use the command line to run it, because that's rather inconvenient (unless there is a way to just double-click and the command line opens the program itself..).
Thanks for your help!
The simple answer that should work for all versions of Windows is to just create a simple batch launcher.
Create a .bat file. I usually just create a new .txt file via "right click > new > text document". Then rename it, highlight everything, including the extension, and rename it to something like run.bat. The .bat part is important. Once you rename it, the icon should change to gears. If you can't overwrite the extension, or Windows is still treating it as a text document, you'll need to either manually save it as a bat, or disable "hide file extensions" in the explorer settings so the extension can be changed.
Edit the bat file, and put into it something like:
#echo off
YOUR RUN COMMAND HERE THAT YOU WOULD NORMALLY TYPE MANUALLY
pause
Paste the command that you would normally run manually where the capital text is. The first line is so it doesn't repeat the commands back, and the pause is so if an error happens, the command prompt doesn't immediately close. This gives you a chance to read the error.
Save it and close it. Now, if you double click on the bat file, your program should run.
Multiple ways
if it's for occasional use and for one script only I would pack it
to a Windows executable with Ocra, then you can double click
the .exe itself or a link to it
same as above but use jRuby and create a .jar file, not for beginners though
the easiest: if you configure Windows to start/run .rb files with your ruby.exe you can double click the .rb files itself and they
will execute, they will have the red Ruby stone icon
if you run a .reg file to enable drap and drop on .rb files you can combine the previous technique to drop files on the script and
they will be the parameters to the script, see my answer here for the reg file
my favorite: copy the .rb to your windows "C:\Users\your_user\AppData\Roaming\Microsoft\Windows\SendTo\"
folder, then you can right click file(s) or folder(s) and select
sendto and select your script, the files or folder will again be the
parameters for your script
you can create a .bat or .cmd file that starts with the path to your ruby.exe and the script as parameter, use rubyw.exe if you
don't want output

Executing a command-line .exe file

I have a .exe file converted from a .jar.
It is a command based application, so I have to start it with a batch script. Here is the batch script:
#echo off
cd C:\desktop\plant-text-adventure-win
start planttextadventure
pause
When I double click on the batch script, this happens: Windows could not find 'planttextadventure'. Please confirm if you have input the correct name and retry.
I don't know what is happening, I have no idea about cmd as I use Mac, but I can confirm I have an executable called planttextadventure.exe in a folder called plant-text-adventure-win.
You should test your batch file by executing it within a shell.
Simply enter within the start menu the command cmd to open up a shell. Within this black box you could now simply enter the commands from your batch script and lookout for some error message.
If you look at your script I would guess that the cd command (to change the current directory) is not correct. Maybe you should replace it with
cd %USERPROFILE%\Desktop\plant-text-adventure-win
because the desktop folder is on a default installation not directly under the root drive but within the user profile available.
Another solution to get this thing to work, is by opening the windows explorer, going to the .exe file you wish to execute and drag & drop the .exe file with a right mouse click onto the desktop.
Then a context menu appears and you select the option Create shortcut here.

Shortcut Ghost: Running a Shortcut as the File?

I'm attempting to generate a shortcut that will run an executable file called WAVistaWin7.exe. Whenever the shortcut generates, I'll double-click it, and it will say "WAVistaWin7.exe cannot find 'wa.exe'." wa.exe is inside of the folder that it belongs. I then attempt to put a Batch file called run.bat containing two lines:
#echo off
WAVistaWin7.exe
I redirect the shorcut to run this file, and the Batch file states that it cannot find WAVistaWin7.exe. It's becoming evident that the shortcut is running independently of the file. Note that whenever I run either WAVistaWin7.exe or run.bat inside of the folder directly it works. How can I get the shortcut to run as the file?
It looks like you need to set your working directory. In the shortcut properties, you can set the "Start in" folder.
Alternatively, in your batch file you can change to the appropriate folder:
#echo off
pushd C:\Program Files\WA
WAVistWin7.exe

"Register" an .exe so you can run it from any command line in Windows

How can you make a .exe file accessible from any location in the Windows command window? Is there some registry entry that has to be entered?
You need to make sure that the exe is in a folder that's on the PATH environment variable.
You can do this by either installing it into a folder that's already on the PATH or by adding your folder to the PATH.
You can have your installer do this - but you may need to restart the machine to make sure it gets picked up.
Windows 10, 8.1, 8
Open start menu,
Type Edit environment variables
Open the option Edit the system environment variables
Click Environment variables... button
There you see two boxes, in System Variables box find path variable
Click Edit
a window pops up, click New
Type the Directory path of your .exe or batch file ( Directory means exclude the file name from path)
Click Ok on all open windows and restart your system restart the command prompt.
You can add the following registry key:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\myexe.exe
In this key, add the default string value containing the path to the exe file.
You have to put your .exe file's path into enviroment variable path. Go to "My computer -> properties -> advanced -> environment variables -> Path" and edit path by adding .exe's directory into path.
Another solution I personally prefer is using RapidEE for a smoother variable editing.
Rather than putting the executable into a directory on the path, you should create a batch file in a directory on the path that launches the program. This way you don't separate the executable from its supporting files, and you don't add other stuff in the same directory to the path unintentionally.
Such batch file can look like this:
#echo off
start "" "C:\Program Files (x86)\Software\software.exe" %*
Let's say my exe is C:\Program Files\AzCopy\azcopy.exe
Command/CMD/Batch
SET "PATH=C:\Program Files\AzCopy;%PATH%"
PowerShell
$env:path = $env:path + ";C:\Program Files\AzCopy"
I can now simply type and use azcopy from any location from any shell inc command prompt, powershell, git bash etc
It is very simple and it won't take more than 30 seconds.
For example the software called abc located in D:/Softwares/vlc/abc.exe
Add the folder path of abc.exe to system environment variables.
My Computer -> Click Properties -> Click Advanced system settings -> Click Environment Variables
Click on Ok.
now you can just open cmd prompt and you can launch the software from anywhere.
to use abc.exe just type abc in the command line.
it's amazing there's no simple solution for such a simple task on windows,
I created this little cmd script that you can use to define aliases on windows (instructions are at the file header itself):
https://gist.github.com/benjamine/5992592
this is pretty much the same approach used by tools like NPM or ruby gems to register global commands.
Simple Bash-like aliases in Windows
To get global bash-like aliases in Windows for applications not added to the path automatically without manually adding each one to the path, here's the cleanest solution I've come up with that does the least amount of changes to the system and has the most flexibility for later customization:
"Install" Your Aliases Path
mkdir c:\aliases
setx PATH "c:\aliases;%PATH%"
Add Your Alias
Open in New Shell Window
To start C:\path to\my program.exe, passing in all arguments, opening it in a new window, create c:\aliases\my program.bat file with the following contents(see NT Start Command for details on the start commmand):
#echo off
start "myprogram" /D "C:\path to\" /W "myprogram.exe" %*
Execute in Current Shell Window
To start C:\path to\my program.exe, passing in all arguments, but running it in the same window (more like how bash operates) create c:\aliases\my program.bat file with the following contents:
#echo off
pushd "C:\path to\"
"my program.exe" %*
popd
Execute in Current Shell Window 2
If you don't need the application to change the current working directory at all in order to operate, you can just add a symlink to the executable inside your aliases folder:
cd c:\aliases\
mklink "my program.exe" "c:\path to\my program.exe"
Add to the PATH, steps below (Windows 10):
Type in search bar "environment..." and choose Edit the system environment variables which opens up the System Properties window
Click the Environment Variables... button
In the Environment Variables tab, double click the Path variable in the System variables section
Add the path to the folder containing the .exe to the Path by double clicking on the empty line and paste the path.
Click ok and exit. Open a new cmd prompt and hit the command from any folder and it should work.
If you want to be able to run it inside cmd.exe or batch files you need to add the directory the .exe is in to the %path% variable (System or User)
If you want to be able to run it in the Run dialog (Win+R) or any application that calls ShellExecute, adding your exe to the app paths key is enough (This is less error prone during install/uninstall and also does not clutter up the path variable)
You may also permanently (after reboots) add to the Path variable this way:
Right click My Computer -> Click Properties -> Click Advanced system settings -> Click Environment Variables
Reference: Change System/User Variables
Put it in the c:\windows directory or add your directory to the "path" in the environment-settings (windows-break - tab advanced)
regards,
//t
In order to make it work
You need to modify the value of the environment variable with the name key Path, you can add as many paths as you want separating them with ;. The paths you give to it can't include the name of the executable file.
If you add a path to the variable Path all the excecutable files inside it can be called from cmd or porweshell by writing their name without .exe and these names are not case sensitive.
Here is how to create a system environment variable from a python script:
It is important to run it with administrator privileges in order to make it work. To better understand the code, just read the comments on it.
Tested on Windows 10
import winreg
# Create environment variable for call the program from shell, only works with compiled version
def environment_var(AppPath):
# Point to the registry key of the system environment variables
key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control\Session Manager\Environment')
def add_var(path):
# Add the variable
winreg.SetValueEx(key, 'Path', 0, winreg.REG_SZ, path)
winreg.CloseKey(key)
try:
# Try to get the value of the Path variable
allPaths = winreg.QueryValueEx(key, 'Path')[0]
except Exception:
# Create the Path variable if it doesn't exist
add_var(path=AppPath)
return
# Get all the values of the existing paths
Path=allPaths.split(';')
# If the Path is empty, add the application path
if Path == ['']:
add_var(path=AppPath)
return
# Check if the application path is in the Path variable
if AppPath not in Path:
# Add the application path to the Path environment variable and add keep the others existing paths
add_var(path=AppPath+';'+allPaths)
# Only run this if the module is not imported by another
if __name__ == "__main__":
# Run the function
environment_var(AppPath=".")
You can find more information in the winreg documentation
You can also move your files to C:\Windows, but you need to use Administrator privileges and pay attention.
What did I mean with pay attention?
You need pay attention because you can also do some messes with Windows system files (Windows may not even work anymore) if you modify, delete, and do some changes incorrectly and accidentally in this folder...
Example: Don't add a file that have the same name of a Windows file
This worked for me:
put a .bat file with the commands you need (I use to run .py script into this) into a FOLDER,
go in the variable environment setting (type var in the search bar and it will show up)
in the global settings
choose path,
then modify,
then add the path to your .bat file (without the .bat file)
close everything: done.
Open the cmd, write the name of the .bat file and it will work
Example
Want to open chrome on a specific link
create a .bat file with this (save it as blog.bat for example)
start "" "https://pythonprogramming.altervista.org/"
go in enviromental variable settings from the search bar in the bottom left of the window desktop
go in enviromental variables (bottom button) then in path (bottom)
add the path, for example G:\myapp_launcher
click apply or ok
Now open cmd and write blog: chrome will open on that page
Do the same to open a file... create a .bat in the folder G:\myapp_launcher (or whatever you called the folder where you put the batch file), call it run.bat or myapp.bat or whatever (write inside of it start filemane.pdf or whatever file you want to open) and after you saved it, you can run that file from cmd with run or myapp or whatever you called your batch file.
Use a 1 line batch file in your install:
SETX PATH "C:\Windows"
run the bat file
Now place your .exe in c:\windows, and you're done.
you may type the 'exename' in command-line and it'll run it.
Another way could be through adding .LNK to your $PATHEX.
Then just create a shortcut to your executable (ie: yourshortcut.lnk) and put it into any of the directories listed within $PATH.
WARNING NOTE:
Know that any .lnk files located in any directories listed in your $PATH are now "PATH'ed" as well. For this reason, I would favor the batch file method mentionned earlier to this method.
I'm not a programmer or anything of the sort, but here's my simple solution:
Create a folder in which you'll be putting SHORTCUTS for all the programs you want to register;
Add that folder to the PATH;
Put all the shortcuts you want in the folder you created in the first step (context menu, New, Shortcut...) The SHORTCUT NAME will have be the be summoned when calling the program or function... NOT THE TARGET FILE NAME.
This will keep you from unintentionally putting files you don't want in the PATH.
Feel free to drop a comment if you think this answer needs to be improved. Cheers 🍻.
P.S. No system or File Explorer restart needed. 😀
Best way is to add the folder path for the .EXE file to Path values in the environment variable.
I'm not sure what versions of Windows this works with, but I put some useful .bat and .exe files into:
%LOCALAPPDATA%\Microsoft\WindowsApps
(equivalent to %USERPROFILE%\AppData\Local\Microsoft\WindowsApps)
which seems to be on my default PATH. I'd be interested to see if this were the general case.
DOSKEY is a Microsoft version of 'alias'. That function is already built into all versions of Windows (and most versions of DOS)
doskey fred=c:\myApps\myprog.exe
You'll want to load that every time you open a command prompt. Which you can do by any number of different methods. One way is to
Make a file containing all the doskey macros you want:
doskey fred=c:\whatever.exe
doskey alan=c:\whateverelse.exe
Change the file type / file name / file extension to .CMD or .BAT
ren myfile.txt myfile.CMD
Add the CMD/BAT file to your command processor autoruns key:
reg ADD \\HKCU\Software\Microsoft\Command Processor /v autorun /t REG_SZ /d myfile.CMD
For more information see
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/doskey
and
https://serverfault.com/a/1049766/142882
(serverfault.com/questions/95404/is-there-a-global-persistent-cmd-history)
Should anyone be looking for this after me
here's a really easy way to add your Path.
Send the path to a file like the image shows,
copy and paste it from the file and add the
specific path on the end with a preceding semicolon
to the new path. It may be needed to be adapted prior
to windows 7, but at least it is an easy starting point.
Command Prompt Image to Export PATH to text file
The best way to do this is just install the .EXE file into the windows/system32 folder. that way you can run it from any location. This is the same place where .exe's like ping can be found

BAT file to open CMD in current directory

I have many scripts which I interact with from the command line. Everytime I need to use them, I have to open a command line window and copy+paste and CD to the path to the directory they are in. This is tedious (they are in a rather deep file system, so typing out the full path is a pain, copy+paste is better but not much). I tried to create a .BAT file that I could double-click on that would open a new command-line window in the folder the .bat file exists in but it does not work. It opens a new window, but the working directory is not the directory that .bat file is in. Here's what I've got after much googling (My cmd skills ain't so great):
cd %CD%
cmd.exe
I know from when I used Linux that Konqueror had a "Command-line window here" feature, and that's the effect I'm trying to get on Windows.
you probably want to do this:
cd /d %~dp0
cmd.exe
this will set your current directory to the directory you have the batch file in
Create a file named open_dos_here.cmd with the following lines:
%~d1
cd "%~p1"
call cmd
Put this file at any folder.
Then, go to your Send To folder (Win+E; Alt+D;shell:sendto;Enter).
Create a shortcut to point to this open_dos_here.cmd
Then, in any folder, select any file or sub-folder. Right-click and select "Send To" and then select open_dos_here.cmd to open the DOS in that folder.
You can just enter cmd into the address bar in Explorer and it starts up in that path. Likewise for PowerShell.
There's a simpler way -
start /d "folder path"
As a more general solution you might want to check out the Microsoft Power Toy for XP that adds the "Open Command Window Here" option when you right-click: http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx
In Vista and Windows 7, you'll get that option if you hold down shift and right-click (this is built in).
I'm thinking that if you are creating a batch script that relies on the Current Directory being set to the folder that contains the batch file, that you are setting yourself up for trouble when you try to execute the batch file using a fully qualified path as you would from a scheduler.
Better to add this line to your batch file too:
REM Change Current Directory to the location of this batch file
CD /D %~dp0
unless you are fully qualifying all of your paths.
Another solution is to use a shortcut file to cmd.exe instead of a batch file.
Edit the shortcut's start in property to %~dp0.
You achieve the same thing, except it has the Cmd icon (and you can change this).
Some people don't like clicking on batch files without knowing what's in them, and some corporate network drives have a ban on .bat files...
The simplest command to do this:
start
You can always run this in command line to open new command line window in the same location. Or you can place it in your .bat file.
Most simple way in explorer is to Shift + right mouse click on the folder or on an empty space in the folder and click on Open command prompt here.
CMD will then start in that folder
I must say, I'm not sure if it works for Windows Vista and below, but it surely works for Windows 7, 8, 8.1 and 10.
Referring to answer of #Chris,
We can also go to parent directory of batch file and run commands using following
cd /d %~dp0..
<OTHER_BATCH_COMMANDS>
cmd.exe
To understand working of command cd /d %~dp0.. please refer below link
What does it mean by command cd /d %~dp0 in Windows
You could add a context menu entry through the registry:
Navigate in your Registry to
HKEY_LOCAL_MACHINE/Software/Classes/Folder/Shell
and create a key called "Command Prompt" without the quotes.
Set the default string to whatever text you want to appear in the right-click menu.
Create a new key within your newly created command prompt named "command," and set the default string to
cmd.exe /k pushd %1
You may need to add %SystemRoot%\system32\ before the cmd.exe if the executable can't be found.
The changes should take place immediately. Right click a folder and your new menu item should appear.
Also see http://www.petri.co.il/add_command_prompt_here_shortcut_to_windows_explorer.htm
When you are in the desired folder , just type CMD in your address bar
A bit late to the game but if I'm understanding your needs correctly this will help people with the same issue.
Two solutions with the same first step:
First navigate to the location you keep your scripts in and copy the filepath to that directory.
First Solution:
Click "Start"
Right-click "Computer" (or "My Computer)
Click "Properties"
On the left, click "Advanced System Settings"
Click "Environment Variables"
In the "System Variables" Box, scroll down and select "PATH"
Click "Edit"
In the "Variable Value" field, scroll all the way to the right
If there isn't a semi-colon (;) there yet, add it.
Paste in the filepath you copied earlier.
End with a semi-colon.
Click "OK"
Click "OK" again
Click "OK" one last time
You can now use any of your scripts as if you were already that folder.
Second Solution: (can easily be paired with the first for extra usefulness)
On your desktop create a batch file with the following content.
#echo off
cmd /k cd "C:\your\file\path"
This will open a command window like what you tried to do.
For tons of info on windows commands check here: http://ss64.com/nt/
Create a new file startCmdLine.bat in your directory and put this line in it
call cmd
That is it. Now double click on the .bat file. It works for me.
You can replace call with start, it will also work.
this code works for me
name it cmd.bat
#echo off
title This is Only A Test
echo.
:Loop
set /p the="%cd%"
%the%
echo.
goto loop
you can try:
shift + right click
then, click on Open command prompt here
Inside given folder click on the top Adddress Bar and type cmd and click enter
It will open command prompt with current folder address.
You can simply create a bat file in any convenient place and drop any file from the desired directory onto it.
Haha. Code for this:
cmd

Resources