How-to: Create and Run a CMD batch file

To prepare a new batch script, save the file as plain ASCII text with the file extension .CMD

Run a batch file

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> Demo.cmd
or
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.

It is also possible to run batch scripts with the old (Windows 95 style) .BAT extension, but be aware that these will run in 16 bit compatibility mode, and that sets the ERRORLEVEL according to the old MSDOS rules.

View the startup command line

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:
C:\WINDOWS\system32\cmd.exe param1

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.

Run a Powershell script

To run a PowerShell script from the CMD shell:

C:\> powershell -file "c:\batch\demo.ps1"

With arguments:

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

Run a VBScript file

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

Related

Run a script from PowerShell
Run a script from VBScript


 
Copyright © SS64.com 1999-2020
Some rights reserved