How do you make a batch file into a cmd comamnd - windows

I have written a batch file in my user folder, which I use a lot. Is there any way that I can call it from cmd when I am working in a different folder, without writing out the full path?

The location has to be in the system %PATH% for it to be executable directly in cmd. You can see the current %PATH% by typing in echo %PATH% in the cmd.
So you have two options: Either add your script directory to the %PATH%, or put your script in a location that is already contained in the %PATH%.
To add the directory to %PATH%, selecting System from the Control Panel, select the 'Advanced' tab, then the 'Environment Variables' button and then find the PATH (user or system) and edit it. Just append ";" to it.
But adding the entire directory can be dangerous as it will let all executables in your script directory be accessible directly from cmd. A better way, in my opinion, is to copy your script to a directory that is already there in %PATH%, like Windows\System32.

Related

How to run application from command prompt with arguments?

I have an application named DriveMaster which I want to run from command line with different arguments. The application is residing in:
"C:\Program Files (x86)\ULINK DM2012 PRO NET\v970\DriveMaster.exe\"
Now in Windows - Run, if I open command prompt and want to give a command like:
DriveMaster /s:Scriptname.srt
This should be able to launch DriveMaster with that particular script.
How can I do this? What should I need to add in the Environment variables so that I can run the application from command prompt?
In Windows 7:
In the menu Start click Computer
In the context menu, select System Properties
Select Advanced System Settings -> tab Advanced
Select Environment Variables Menu System Variables to find the PATH variable and click it.
In the editing window, change the PATH, adding value: ; C:\Program Files (x86)\ULINK DM2012 PRO NET\v970
Open Run and type: DriveMaster /s:Scriptname.srt
That's all.
When you're in the command prompt the working directory is given in the prompt:
C:\Users>
Here, I'm in the folder C:\Users. If I want to run a program or a script in the folder I'm currently in, I can use its name alone (e.g. DriveMaster). If the program is outside my working directory, I can't call it like that because there could be many DriveMasters in different folders throughout my computer. I can either change my directory to be the one that has this program, or I can specify where in the filesystem it's located.
Changing the directory and running:
C:\Users> cd "C:\Program Files (x86)\ULINK DM2012 PRO NET\v970\"
C:\Program Files (x86)\ULINK DM2012 PRO NET\v970> DriveMaster
Specifying the full path:
"C:\Program Files (x86)\ULINK DM2012 PRO NET\v970\DriveMaster"
(I need to use quotes here because the folder names have spaces and my command prompt may not know if it's part of the folder name or the beginning of another command or argument.)
On the same line I call the program, I can choose a number of arguments (also called options, switches, flags) to change the way to program behaves. If my program accepts another file and wants it in the form /s: and-then-the-filename, that file also needs to be in my working directory. If it lives somewhere else, I can use the full specification, like I've done above.
Environment variables are a little more complicated of a topic, but there is one we might be interested in here. The Path environment variable is a list of folders that the command prompt will look in when you try to use names of files that aren't in your working directory. If I know I'm going to be using this program frequently and like where it is, I can add its folder to my Path so that I can access it with just DriveMaster in the future:
set PATH=%PATH%;C:\Program Files (x86)\ULINK DM2012 PRO NET\v970
(If I mistype that command, though, I could break other things in a way that would be hard to fix.)
In a file name drivemaster.bat whch would be located at some point in the path,
#echo off
setlocal
"C:\Program Files (x86)\ULINK DM2012 PRO NET\v970\DriveMaster.exe" /s:Scriptname.srt
where Scriptname.srt would need to be quoted and supplied with a full pathname if it's not in the current directory.
Oh you want to type DriveMaster /s:Scriptname.srt
Then use
"C:\Program Files (x86)\ULINK DM2012 PRO NET\v970\DriveMaster.exe" %1
in that script in place of the original "c:..." line.
edit : removed stray terminal backslash from ...exe

How to execute a .bat file first instead of an file .exe when both have the same path/name?

My emacs.bat rest in the same bin directory as emacs.exe. This directory is included in the PATH variable (Windows).
Content of emacs.bat:
#echo off "%~dp0emacsclientw.exe" -na "%~dp0runemacs.exe" "%1"
However, whenever I use this command, emacs.exe gets executed instead of the .bat file. How would I go about fixing this?
It seems you could put the emacs.bat in another directory and place that directory earlier in the PATH. Note: if you were to run "emacs" while in the directory containing emacs.exe then the .exe would take precedence.
Edit: Alternatively, you could just type emacs.bat instead of emacs at the command prompt.
Edit 2: As seen in this Answer, you could set the PATHEXT environment variable. Something along the lines of:
PATHEXT=.BAT;.COM;.EXE;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.RB;.RBW

Windows CMD: How to create symbolic link to executable file?

My goal is to add a few executables to my PATH (for example, chrome), so that I can call
> chrome
from the command prompt and it will launch Chrome.
I know I could add Chrome's containing directory to my path (set PATH=%PATH%<chrome_path_here>;), but since I have a few executables I want to add, I'd rather make a new bin directory that contains symbolic links to the actual executables and just add that single directory to my PATH.
The Chrome executable is located at
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
So I tried
> mklink chrome.exe "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
That successfully creates a symbolic link for the files (says so in output, and upon examining with > dir). I know my PATH is set up correctly, b/c when I run > where chrome it finds my new symbolic link.
However, when I try to execute chrome with my new link, nothing happens. A new empty window should appear, but nothing happens. No error message in the command prompt or anything.
What am I doing wrong? Am I misunderstanding symlinks in Windows? This is the approach I use in Linux all the time, but I'm new to Windows Cmd.
Thanks!
Most programs will not run from places other than they install location - which is exactly what happens when you try to run it from symlink.
It would be much easier to create CMD/BAT files in that folder with matching names which will launch programs from locations you want:
REM chrome.cmd
start /b cmd /c "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" %*
With Windows 7 I confirm that symlinks do not work, are simply ignored as reported in the original question.
As Harry states in his comment, shortcuts do work, and to me are simpler and easier than writing a separate script for each new command I want to enable under CMD.
He states that you need to add .lnk to your PATHEXT variable in order to do this. I affirm that this does work, and with .lnk added to PATHEXT I can simply enter the name portion of the shortcut to run the command. For example if my shortcut is named "sublime.lnk" and PATHEXT includes .lnk, I can execute the link with the simple command "sublime". Nice!
As an alternative I found that PATHEXT need not be modified if I simply type in the full name of the shortcut, including the .lnk, at my CMD prompt. E.g., I created a shortcut named "sublime.lnk" under %HOMEPATH%/bin, pointing to "C:\Program Files\Sublime Text 2\sublime_text.exe".
Now by placing %HOMEPATH%\bin in my %PATH% I can run sublime via the command "sublime.lnk".
Either of the above are the best way I know of giving access to various commands from around Windows' filesystem from a CMD prompt. I'm not a Windows expert though, and welcome a better or more standardized solution to this problem.
P.S.: I just found out the hard way that you need to ensure the "Start in:" property of any shortcut you use in this fashion is blanked out, or your program will not start in the directory you invoke the shortcut from.
P.P.S.: On a related note, I discovered how to run Windows Explorer (or its replacement) on the directory your CMD session is logged in to: start ..

help with windows batch scripting basics - execution and calling a separate executable within the script

Newbie to windows scripting. I need help running the .bat file on the command line so I can test it.
I used Text Document as my editor to create the file (opens up also as Notepad).
I performed file "save as" (ALL FILES). If I open up cmd, I can see the file has a .txt extension (myfile.bat.txt). So if I just type in cmd myfile.bat.txt the editor opens. I am not sure how to execute this correctly.
As for the logic in my batch script, I am basically logging into a remote directory (already created the net mount) and now I want to:
run an executeable file
rename some files.
With some research, I written this so far. I have saved it as a .bat file
# echo off
echo This is a batch file to run an executable and rename some files
pause
--run executable file here, just don't know how to do it
x:
cd x:
rename fileA fileB
Any help, good tips/practice would be great. Thanks.
Type in this command in cmd window:
rename myfile.bat.txt myfile.bat
Now you can run the script by simply invoking:
myfile.bat
or
myfile
(provided there's no myfile.exe or myfile.com in the same directory).
If you need to edit the script further, you can either right click it in Explorer and choose Edit or call the editor from the command window:
notepad myfile.bat
To call a program from the script, simply add its name, if it's in the current directory:
someprogram.exe
or the name with the path, if it's somewhere else:
directory\program.exe
or
d:\directory\program.exe
If the name or the path contain spaces, be sure to enclose the entire name & path string in double quotes:
"d:\directory\program name.exe"
you can just type the full name of the program
eg
"c:\program dir\program.exe"
or you can add the program directory to your path environment variable
set PATH=%PATH%;"c:\program dir"
and just type the program name
program
you can also edit your PATH variable in windows http://support.microsoft.com/kb/310519
NOTE: When you save the file in notepad, you want to save it as filename.BAT and select All Files from the second dropdown. If you don't it still gets saved as a .TXT.
A couple of command to consider:
CSCRIPT cscript /? in CMD
START http://ss64.com/nt/start.html
If you're doing say a VBSCRIPT use CSCRIPT to start it. If you're trying to execute another BATCH script or an EXE, use START

"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

Resources