To prepare a new batch script, save the file as plain ASCII text with the file extension .CMD
It is also possible to run batch scripts with the .BAT extension, but this is not recommended unless you need compatibility with Windows 95 (.BAT files will set ERRORLEVEL following inconsistent MS-DOS style rules).
A batch file can be run by double clicking it in Windows explorer, or by typing the name/path at the command line, optionally passing any parameters needed.
From the start menu: START > RUN c:\path_to_scripts\my_script.cmd, OK
If the filename includes any spaces, then you will need to surround the command with quotes:
"c:\path to scripts\my script.cmd"
Open a new CMD prompt by choosing START > RUN cmd, OK
From the command line, enter the name of the script and press return.
C:\Batch> c:\path_to_scripts\my_script.cmd param1 param2
This can be made easier by creating a shortcut for the start menu or taskbar.
To run a batch file from within another batch file, use the CALL command, otherwise the first script will start the second script and immediately exit, so any further commands in the first script will not run.
The environment Variable %CmdCmdLine% will expand into the original command line passed to CMD.EXE
When a batch file is launched from the command line %CmdCmdLine% will return:
When a batch file is launched by double clicking in Windows Explorer or START > RUN, %CMDCMDLINE% will return:
C:\WINDOWS\system32\cmd.exe /c ""C:\demo\batch.cmd param1
The /c can be used to detect the start mode:
Echo %CmdCmdLine% | findstr /c:" /c " >nul && Echo Started with a double click.
To run a PowerShell script from the CMD shell:C:\> powershell -file "c:\batch\demo.ps1"
C:\> powershell -file "c:\batch\demo.ps1" filename1.txt Testing
If the arguments need quotes you will need to triple them so they are escaped:
C:\> powershell -file "c:\batch\demo.ps1" """\Path To\filename1.txt""" """A Test string"""
When calling PowerShell from CMD be aware that a comma is a CMD delimiter, this makes it impossible to pass an array of comma separated values to PowerShell. item1,item2,item3 is treated the same as item1 item2 item3
To run a VBScript from the CMD shell:C:\> cscript c:\batch\demo.vbs
“The method of the enterprising is to plan with audacity and execute with vigor” ~ John Christian Bovee
START - Start a program, command or batch file.
RUN commands Start | Run commands.
How-to: Run a script from PowerShell
How-to: Run a script from VBScript