Start a program, command or batch script (opens in a new window.)
Syntax
START "title" [/D path] [options] "command" [parameters]
Key:
title Text for the CMD window title bar (required.)
path Starting directory.
command The command, batch file or executable program to run.
parameters The parameters passed to the command.
Options:
/MIN Start window Minimized.
/MAX Start window Maximized.
/W or /WAIT Start application and wait for it to terminate.
(see below)
/LOW Use IDLE priority class.
/NORMAL Use NORMAL priority class.
/ABOVENORMAL Use ABOVENORMAL priority class.
/BELOWNORMAL Use BELOWNORMAL priority class.
/HIGH Use HIGH priority class.
/REALTIME Use REALTIME priority class.
/B Start application without creating a new window. In this case
Ctrl-C will be ignored - leaving Ctrl-Break as the only way to
interrupt the application.
/I Ignore any changes to the current environment.
Use the original environment passed to cmd.exe
/NODE The preferred Non-Uniform Memory Architecture (NUMA)
node as a decimal integer.
/AFFINITY The processor affinity mask as a hexadecimal number.
The process will be restricted to running on these processors.
Options for 16-bit WINDOWS programs only
/SEPARATE Start in separate memory space. (more robust) 32 bit only.
/SHARED Start in shared memory space. (default) 32 bit only.
Always include a TITLE this can be a simple string like “My Script” or just a pair of empty quotes “”
According to the Microsoft documentation, the title is optional, but depending on the other options chosen you can have problems if it is omitted.
If command is an internal cmd command or a batch file then the command processor is run with the /K switch to cmd.exe. This means that the window will remain after the command has been run.
In a batch script, a START command without /wait will run the program and just continue, so a script containing nothing but a START command will close the CMD console and leave the new program running.
Document files can be invoked through their file association just by typing the name of the file as a command.
e.g. START “” MarchReport.DOC will launch the application associated with the .DOC file extension and load the document.
To minimise any chance of the wrong exectuable being run, specify the full path to command or at a minimum include the file extension: START “” notepad.exe
If you START an application without a file extension (for example WinWord instead of WinWord.exe)then the PATHEXT environment variable will be read to determine which file extensions to search for and in what order.
The default value for the PATHEXT variable is: .COM;.EXE;.BAT;.CMD
Start /Wait
The behaviour of START /Wait will vary depending on the item being started, for example
Echo Starting START /wait "demo" calc.exe Echo Done
The above will start the calculator and wait before continuing. However if you replace calc.exe with Winword.exe, to run Word instead, then the /wait will stop working, this is because Winword.exe is a stub which launches the main Word application and then exits.
A similar problem will occur when starting a batch file, by default START will run the equivalent of CMD /K which opens a second command window and leaves it open. In most cases you will want the batch script to complete, then just close it’s CMD console and resume the initial batch script. This can be done by explicitly running CMD /C …
Echo Starting START /wait "demo" CMD /c demoscript.cmd Echo Done
Add /B to have everything run in a single window.
In a batch file, an alternative is to use TIMEOUT to delay processing of individual commands.
START vs CALL
Starting a new process with CALL, is very similar to running START /wait, in both cases the calling script will (usually) pause until the second script has completed.
Starting a new process with CALL, will run in the same shell environment as the calling script. For a GUI application this makes no difference, but a second ‘called’ batch file will be able to change variables and pass those changes back to the caller.
In comparison START will instantiate a new CMD.exe shell for the called batch. This will inherit variables from the calling shell, but any variable changes will be discarded when the second script ends.
Run a program
To start a new program (not a batch script), you don’t have to use CALL or START, simply enter the path/file to be executed, either on the command line or within a batch script.
On the command line, CMD.EXE does not wait for the application to terminate and control immediately returns to the command prompt.
Within a command script CMD.EXE will pause the initial script and wait for the application to terminate before continuing.
If you run one batch script from another without using either CALL or START, then the first script is terminated and the second one takes over.
Multiprocessor systems
Processor affinity is assigned as a hex number but calculated from the binary positions (similar to NODRIVES)
Hex Binary Processors 1 00000001 Proc 1 3 00000011 Proc 1+2 7 00000111 Proc 1+2+3 C 00001100 Proc 3+4 etc
Specifying /NODE allows processes to be created in a way that leverages memory locality on NUMA systems. For example, two processes that communicate with each other heavily through shared memory can be created to share the same preferred NUMA node in order to minimize memory latencies. They allocate memory from the same NUMA node when possible, and they are free to run on processors outside the specified node.
start /NODE 1 app1.exe start /NODE 1 app2.exe
These two processes can be further constrained to run on specific processors within the same NUMA node.
In the following example, app1 runs on the low-order two processors of the node, while app2 runs on the next two processors of the node. This example assumes the specified node has at least four logical processors. Note that the node number can be changed to any valid node number for that computer without having to change the affinity mask.
start /NODE 1 /AFFINITY 0x3 app1.exe start /NODE 1 /AFFINITY 0xc app2.exe
Running executable (.EXE) files
When a file that contains a .exe header, is invoked from a CMD prompt or batch file (with or without START), it will be opened as an executable file. The filename extension does not have to be .EXE. The file header of executable files start with the ‘magic sequence’ of ASCII characters ‘MZ’ (0x4D, 0x5A) The ‘MZ’ being the initials of Mark Zibowski, a Microsoft employee at the time the file format was designed.
Command Extensions
If Command Extensions are enabled, external command invocation through the command line or the START command changes as follows:
Non-executable files can be invoked through their file association just by typing the name of the file as a command. (e.g. WORD.DOC would launch the application associated with the .DOC file extension). This is based on the setting in HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ext\OpenWithList, or if that is not specified, then the file associations – see ASSOC and FTYPE.
When executing a command line whose first token is the string CMD without an extension or path qualifier, then CMD is replaced with the value of the COMSPEC variable. This prevents picking up CMD.EXE from the current directory.
When executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the COMSPEC environment variable. This prevents picking up CMD.EXE from the current directory.
When executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order. The default value for the PATHEXT variable is: .COM;.EXE;.BAT;.CMD Notice the syntax is the same as the PATH variable, with semicolons separating the different elements.
When searching for an executable, if there is no match on any extension, then looks to see if the name matches a directory name. If it does, the START command launches the Explorer on that path. If done from the command line, it is the equivalent to doing a CD /D to that path.
Errorlevels
If the command is successfully started ERRORLEVEL =unchanged, typically this will be 0 but if a previous command set an errorlevel, that will be preserved (this is a bug).
If the command fails to start then ERRORLEVEL = 9059
START /WAIT batch_file – will return the ERRORLEVEL specified by EXIT
Examples
Run a minimised Login script:START "My Login Script" /Min Login.cmd
Start a program and wait for it to complete before continuing:START "" /wait autocad.exe
Open a file with a particular program:START "" "C:\Program Files\Microsoft Office\Winword.exe" "D:\Docs\demo.txt"
Open Windows Explorer and list the files in the current folder (.) :C:\any\old\directory> START .
Connect to a new printer: (this will setup the print connection/driver )START \\print_server\printer_name
Start an application and specify where files will be saved (Working Directory):
START /D C:\Documents\ /MAX "Maximised Notes" notepad.exe
START is an internal command.
-
What is the
STARTCommand? -
Basic Syntax of the
STARTCommand -
Example 1: Opening Notepad
-
Example 2: Opening a URL in the Default Browser
-
Example 3: Running Multiple Commands
-
Example 4: Using START with File Paths
-
Example 5: Starting a Program with Parameters
-
Conclusion
-
FAQ
When it comes to automating tasks in Windows, Batch Scripts are incredibly powerful tools. One of the most useful commands in Batch Scripting is the START command. This command allows you to open applications, documents, or even new command prompt windows, all from a simple script. Whether you’re looking to streamline your workflow or just want to learn a new scripting technique, understanding how to effectively use the START command can significantly enhance your automation capabilities.
In this tutorial, we’ll delve into various ways to utilize the START command in Batch Scripts, providing you with practical examples and explanations to ensure you’re fully equipped to implement it in your projects.
What is the START Command?
The START command in Batch Scripts is a versatile command that allows users to launch applications or files in a new window. It can be particularly handy when you want to run multiple programs simultaneously or when you need to execute a command without interrupting the current command prompt session. By using the START command, you can enhance the efficiency of your scripts, making them more dynamic and user-friendly.
Basic Syntax of the START Command
Before we dive into examples, it’s important to understand the basic syntax of the START command. The general format is:
START ["Title"] [options] "path_to_executable_or_file"
Title: This is an optional parameter that specifies the title of the new window.Options: These can include various flags like/MINto minimize the window or/WAITto wait for the program to finish before continuing.Path: This is the path to the executable or file you want to open.
Understanding this syntax will help you effectively utilize the START command in your Batch Scripts.
Example 1: Opening Notepad
One of the simplest uses of the START command is to open Notepad from a Batch Script. Here’s how you can do it:
@echo off
START notepad.exe
In this example, the script uses the @echo off command to prevent the commands from being displayed in the command prompt. The START notepad.exe command then launches Notepad in a new window. This is a straightforward way to open applications without blocking the command prompt.
Example 2: Opening a URL in the Default Browser
You can also use the START command to open a URL in your default web browser. This can be particularly useful for automating web-related tasks. Here’s an example:
@echo off
START https://www.example.com
In this script, the command START https://www.example.com opens the specified URL in the default web browser. This is especially handy for scripts that require web access, allowing users to quickly navigate to relevant sites without manual input.
Example 3: Running Multiple Commands
The START command can also be used to run multiple commands simultaneously. Here’s a script that demonstrates this:
@echo off
START notepad.exe
START cmd.exe /K echo Hello, World!
In this example, the script starts Notepad and then opens a new command prompt window that displays “Hello, World!” using the /K option. This allows for running multiple processes at once, making your scripts more efficient and interactive.
Example 4: Using START with File Paths
You can also use the START command to open files directly. Here’s how:
@echo off
START "" "C:\path\to\your\file.txt"
In this case, the script opens a text file located at the specified path. The empty quotes "" are used to designate the window title, which is optional. This is useful for quickly accessing files without needing to navigate through folders manually.
Example 5: Starting a Program with Parameters
Sometimes, you may need to start a program with specific parameters. Here’s an example of how to do this:
@echo off
START "" "C:\path\to\your\program.exe" --option1 --option2
In this script, the program specified will launch with the given options. This is particularly useful for applications that support command-line arguments, allowing for greater control over how they run.
Conclusion
The START command in Batch Scripts is a powerful tool that can significantly enhance your automation capabilities. From opening applications to running multiple commands simultaneously, understanding how to use this command effectively can streamline your workflow and make your scripts more dynamic. By experimenting with the various examples provided, you can tailor the START command to fit your specific needs, ultimately improving your efficiency and productivity. Whether you’re a novice or an experienced scripter, mastering the START command will undoubtedly add value to your Batch Scripting toolkit.
FAQ
-
What does the START command do in Batch Scripts?
The START command launches applications or files in a new window, allowing for simultaneous execution of multiple processes. -
Can I use the START command to open websites?
Yes, you can use the START command to open URLs in your default web browser. -
How do I run multiple commands with the START command?
You can run multiple commands by using separate START commands for each application or file you want to launch. -
Is it necessary to use quotes in the START command?
Quotes are used for paths with spaces or to specify window titles, but they are optional for simple commands without spaces. -
Can I pass parameters to programs using the START command?
Yes, you can pass parameters to programs by including them after the program’s path in the START command.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
START [«заголовок»] [/D путь] [/I] [/MIN] [/MAX] [/SEPARATE или
/SHARED] [/LOW или /NORMAL или /HIGH или /REALTIME или
/ABOVENORMAL или /BELOWNORMAL] [/WAIT] [/B]
[команда/программа] [параметры]
Эта команда позволяет запускать в отдельном окне любую программу с заданными исходными параметрами.
-
заголовок- заголовок программы, который будет отображаться в панели заголовка открытого для этой программы окна;
-
/D путь- указание на рабочую папку запускаемой программы, в которой хранятся все необходимые для ее загрузки файлы;
-
/I- запуск программы не в новой среде окружения, а в исходной среде, переданной интерпретатором команд CMD;
-
/B- настройка режима прерывания исполнения программы по нажатию сочетания клавиш Ctrl+C. Если данное приложение не обрабатывает нажатие клавиш Ctrl+C, приостановить его исполнение можно по нажатию клавиш Ctrl+Break;
-
/MIN- запуск программы в окне, свернутом в Панель задач;
-
/MAX- запуск программы в окне, развернутом во весь экран;
-
/SEPARATE- выполнить запуск 16-разрядного приложения Windows в отдельной области памяти;
-
/SHARED- выполнить запуск 16-разрядного приложения Windows в общей области памяти;
-
/LOW- запустить приложение с низким приоритетом на исполнение (idle);
-
/NORMAL- запустить приложение с обычным приоритетом на исполнение (normal);
-
/HIGH- запустить приложение с высоким приоритетом на исполнение (high);
-
/REALTIME- запустить приложение с приоритетом реального времени (realtime);
-
/ABOVENORMAL- запустить приложение с приоритетом выше среднего (abovenormal);
-
/BELOWNORMAL- запустить приложение с приоритетом ниже среднего (belownormal);
-
/WAIT- запустить приложение в режиме ожидания его завершения;
-
команда/программа- путь и имя самой команды или программы. Если при помощи команды START запускается внутренняя команда оболочки CMD либо пакетный файл, новое окно CMD будет запущено с ключом /K, другими словами, оно не будет закрыто по завершении сеанса работы программы. Если вы запускаете какое-либо другое приложение, для него будет открыто стандартное графическое окно Windows XP;
-
параметры- внешние параметры, ключи и переменные, передаваемые программе средой CMD при ее запуске.
ПРИМЕЧАНИЕ
Для вызова исполняемых файлов посредством открытия ассоциированных с ними типов файлов из окна командной консоли достаточно набрать в командной строке полное имя такого файла. Например, при вызове из окна Командная строка файла document.doc, ассоциированного в системе с программой Microsoft Word, Windows автоматически запустит Word на исполнение и загрузит в него этот файл.
При запуске 32-разрядного приложения с графическим интерфейсом из командной строки обработчик команд не ожидает завершения работы приложения перед закрытием его окна и возвратом к приглашению операционной системы. Этот принцип распространяется на все случаи запуска программ, кроме их вызова из пакетных файлов.
В случае если в командной строке не указано расширения файла, обработчик команд использует значение переменной среды PATHEXT с целью определить расширения имен исполняемых файлов и порядок поиска программы в файловой структуре диска. По умолчанию этой переменной присвоены значения .com; .exe; .bat; .cmd. Синтаксис записи значений для данной переменной аналогичен синтаксису для переменной PATH, то есть отдельные элементы разделяются точкой с запятой.
Если в процессе поиска исполняемого файла не было выявлено соответствий ни с одним из зарегистрированных в системе расширений, программа выполняет проверку соответствия указанного имени папки. Если имя папки соответствует указанному, то команда START запускает Проводник, открывающий эту папку для обзора.
К разделу
- SS64
- CMD
- How-to
Start a program, command or batch script, opens in a new/separate Command Prompt window.
Syntax
START "title" [/D path] [options] "command" [parameters]
Key:
title Text for the CMD window title bar (required.)
path Starting directory.
command The command, batch file or executable program to run.
parameters The parameters passed to the command.
Options:
/MIN Start window Minimized.
/MAX Start window Maximized.
/W or /WAIT Start application and wait for it to terminate.
(see below)
/LOW Use IDLE priority class.
/NORMAL Use NORMAL priority class.
/ABOVENORMAL Use ABOVENORMAL priority class.
/BELOWNORMAL Use BELOWNORMAL priority class.
/HIGH Use HIGH priority class.
/REALTIME Use REALTIME priority class.
/B Start application without creating a new window. In this case
Ctrl-C will be ignored - leaving Ctrl-Break as the only way to
interrupt the application.
/I Ignore any changes to the current environment, typically made with SET.
Use the original environment passed to cmd.exe
/NODE The preferred Non-Uniform Memory Architecture (NUMA)
node as a decimal integer.
/AFFINITY The processor affinity mask as a hexadecimal number.
The process will be restricted to running on these processors.
Options for running 16-bit Windows programs, on Windows 10 only:
/SEPARATE Start in separate memory space. (more robust) 32 bit only.
/SHARED Start in shared memory space. (default) 32 bit only.
Always include a TITLE this can be a simple string like «My Script» or just a pair of empty quotes «»
According to the Microsoft documentation, the title is optional, but depending on the other options chosen you can have problems if it is omitted.
If command is an internal cmd command or a batch file then the command processor CMD.exe is run with the /K switch. This means that the window will remain after the command has been run.
In a batch script, a START command without /wait will run the program and just continue, so a script containing nothing but a START command will close the CMD console and leave the new program running.
Document files can be invoked through their file association just by typing the name of the file as a command.
e.g. START «» MarchReport.docx will launch the application associated with the .docx file extension and load the document.
To minimise any chance of the wrong exectuable being run, specify the full path to command or at a minimum include the file extension: START «» notepad.exe
If you START an application without a file extension (for example WinWord instead of WinWord.exe)then the PATHEXT environment variable will be read to determine
which file extensions to search for and in what order.
The default value for the PATHEXT variable is: .COM;.EXE;.BAT;.CMD
Start — run in parallel
The default behaviour of START is to instantiate a new process that runs in parallel with the main process. For arcane technical reasons, this does not work for some types of executable, in those cases the process will act as a blocker, pausing the main script until it’s complete.
In practice you just need to test it and see how it behaves.
Often you can work around this issue by creating a one line batch script (runme.cmd ) to launch the executable, and then call that script with START runme.cmd
Start /Wait
The /WAIT option should reverse the default ‘run in parallel’ behaviour of START but again your results will vary depending on the item being started, for example:
Echo Starting START /wait "job1" calc.exe Echo DoneThe above will start the calculator and wait before continuing. However if you replace calc.exe with Winword.exe, to run Word instead, then the /wait will stop working, this is because Winword.exe is a stub which launches the main Word application and then exits.
A similar problem will occur when starting a batch file, by default START will run the equivalent of CMD /K which opens a second command window and leaves it open. In most cases you will want the batch script to complete and then just close its CMD console to resume the initial batch script. This can be done by explicitly running CMD /C …
Echo Starting START /wait "demojob" CMD /c demoscript.cmd Echo DoneAdd /B to have everything run in a single window.
In a batch file, an alternative is to use TIMEOUT to delay processing of individual commands.
START vs CALL
Starting a new process with CALL, is very similar to running START /wait, in both cases the calling script will (usually) pause until the second script has completed.
Starting a new process with CALL, will run in the same shell environment as the calling script. For a GUI application this makes no difference, but a second ‘called’ batch file will be able to change variables and pass those changes back to the caller.
In comparison START will instantiate a new CMD.exe shell for the called batch. This will inherit variables from the calling shell, but any variable changes will be discarded when the second script ends.
Run a program
To start a new program (not a batch script), you don’t have to use CALL or START, just enter the path/file to be executed, either on the command line or within a batch script. This will behave as follows:
- On the command line, CMD.EXE does not wait for the application to terminate and control immediately returns to the command prompt.
- Running a program from within a batch script, CMD.EXE will pause the initial script and wait for the application to terminate before continuing.
- If you run one batch script from another without using either CALL or START, then the first script is terminated and the second one takes over.
Search order:
- Running a program from CMD will search first in the current directory and then in the PATH.
- Running a program from PowerShell will search first in the PATH and then in the current directory.
- The Windows Run Line (win+r) will search first in App Paths [defined in HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths] and then the PATH
Multiprocessor systems
Processor affinity is assigned as a hex number but calculated from the binary positions (similar to NODRIVES)
Hex Binary Processors
1 00000001 Proc 1
3 00000011 Proc 1+2
7 00000111 Proc 1+2+3
C 00001100 Proc 3+4 etcSpecifying /NODE allows processes to be created in a way that leverages memory locality on NUMA systems. For example, two processes that communicate with each other heavily through shared memory can be created to share the same preferred NUMA node in order to minimize memory latencies. They allocate memory from the same NUMA node when possible, and they are free to run on processors outside the specified node.
start /NODE 1 app1.exe
start /NODE 1 app2.exeThese two processes can be further constrained to run on specific processors within the same NUMA node.
In the following example, app1 runs on the low-order two processors of the node, while app2 runs on the next two processors of the node. This example assumes the specified node has at least four logical processors. Note that the node number can be changed to any valid node number for that computer without having to change the affinity mask.
start /NODE 1 /AFFINITY 0x3 app1.exe
start /NODE 1 /AFFINITY 0xc app2.exe
Running executable (.EXE) files
When a file that contains a .exe header, is invoked from a CMD prompt or batch file (with or without START), it will be opened as an executable file. The filename extension does not have to be .EXE. The file header of executable files start with the ‘magic sequence’ of ASCII characters ‘MZ’ (0x4D, 0x5A) The ‘MZ’ being the initials of Mark Zibowski, a Microsoft employee at the time the file format was designed.
Command Extensions
If Command Extensions are enabled, external command invocation through the command line or the START command changes as follows:
Non-executable files can be invoked through their file association just by typing the name of the file as a command. (e.g. example.docx would launch the application associated with the .docx file extension). This is based on the setting in HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ext\OpenWithList, or if that is not specified, then the file associations — see ASSOC and FTYPE.
When executing a command line whose first token is the string CMD without an extension or path qualifier, then CMD is replaced with the value of the COMSPEC variable. This prevents picking up CMD.EXE from the current directory.
When executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the COMSPEC environment variable. This prevents picking up CMD.EXE from the current directory.
When executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order. The default value for the PATHEXT variable is: .COM;.EXE;.BAT;.CMD Notice the syntax is the same as the PATH variable, with semicolons separating the different elements.
When searching for an executable, if there is no match on any extension, then looks to see if the name matches a directory name. If it does, the START command launches the Explorer on that path. If done from the command line, it is the equivalent to doing a CD /D to that path.
Errorlevels
If the command is successfully started ERRORLEVEL =unchanged, typically this will be 0 but if a previous command set an errorlevel, that will be preserved (this is a bug).
If the command fails to start then ERRORLEVEL = 9059
START /WAIT batch_file — will return the ERRORLEVEL specified by EXIT
START is an internal command.
Examples
Start a program in the current directory:
START «Demo Title» example.exe
Start a program giving a fulll path:
START «Demo 2» /D «C:\Program Files\ACME Corp\» «example.exe»
Alternatively:
START «Demo 2» «C:\Program Files\ACME Corp\example.exe»
or:
CD /d «C:\Program Files\ACME Corp\»
START «Demo 2» «example.exe»
Start a program and wait for it to complete before continuing:
START «Demo 3» /wait autocad.exe
Open a file with a particular program:
START «Demo 4» «C:\Program Files\Microsoft Office\Winword.exe» «D:\Docs\demo.txt»
Run a minimised Login script:
CMD.exe /C START «Login Script» /Min CMD.exe /C Login.cmd
In this example the first CMD session will terminate almost immediately and the second will run minimised.
The first CMD is required because START is a CMD internal command. An alternative to this is using a shortcut set to open minimised.
Open Windows Explorer and list the files in the current folder (.) :
C:\any\old\directory> START .
Open a webpage in the default browser, note the protocol is required (https://):
START
https://ss64.com
Open a webpage in Microsoft Edge:
%windir%\explorer.exe microsoft-edge:https://ss64.com
or with a hard-coded path:
«C:\Program Files (x86)\Microsoft Edge\Application\msedge.exe»https://ss64.com"%windir%\explorer.exe shell:Appsfolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge" https://ss64.com
Connect to a new printer: (this will setup the print connection/driver):
START \\print_server\printer_name
Start an application and specify where files will be saved (Working Directory):
START /D C:\Documents\ /MAX «Maximised Notes» notepad.exe
“Do not run; scorn running with thy heels” ~ Shakespeare, The Merchant of Venice
Related commands
WMIC process call create «c:\some.exe»,»c:\exec_dir» — This method returns the PID of the started process.
CALL — Call one batch program from another.
CMD — can be used to call a subsequent batch and ALWAYS return even if errors occur.
TIMEOUT — Delay processing of a batch file/command.
TITLE — Change the title displayed above the CMD window.
RUN commands Start ➞ Run commands.
How-to: Run a script — How to create and run a batch file.
How-to: Autoexec — Run commands at startup.
ScriptRunner — Run one or more scripts in sequence.
Q162059 — Opening Office documents.
Equivalent PowerShell: Start-Process — Start one or more processes.
Equivalent bash command (Linux) : open — Open a file in it’s default application.
Equivalent macOS command: open — Open a file in a chosen application.
Copyright © 1999-2025 SS64.com
Some rights reserved
Команда START в операционной системе Windows предоставляет широкий спектр возможностей для запуска приложений и команд в отдельном окне командной строки. Это важный инструмент для системных администраторов, разработчиков и других продвинутых пользователей, позволяющий гибко управлять процессами и окнами консоли.
Общие сведения
Команда START отличается высокой функциональностью и универсальностью. Она позволяет запускать процессы с различными параметрами, задавая приоритет, выделяя процессорное время, определяя рабочий каталог и заголовок окна. Все это делает команду невероятно полезной в различных сценариях от автоматизации задач до разработки и тестирования программного обеспечения.
Одна из основных причин популярности команды START – ее способность предоставлять контроль над запуском приложений и процессов. Это объясняется наличием множества параметров, которые позволяют точно настраивать поведение запускаемых программ. В статье рассмотрены все основные параметры и возможности этой команды.
Параметры командной строки
Заголовок окна
Первым параметром команды START является «заголовок». Он указывается в двойных кавычках и определяет текст, который будет отображаться в заголовке окна командной строки. Это полезно, если у вас открыто несколько окон и вам необходимо быстро различать их. Например:
START "Мой заголовок" програма.exe
Рабочий каталог (/D путь)
Рабочий каталог (/D путь) позволяет запускать программу в определенной директории. Это полезно для тех приложений, которые зависят от файлов, расположенных в конкретном каталоге. Например:
START /D "C:\Путь\К\Каталогу" программа.exe
Использование рабочей директории особенно важно для скриптов и командных файлов, которые обращаются к файлам и ресурсам по относительным путям.
Запуск в новой среде (/I)
Параметр /I указывает, что новая среда для запущенной команды должна быть исходной средой, переданной cmd.exe, а не текущей средой:
START /I программа.exe
Этот параметр пригодится в ситуациях, когда требуется, чтобы программа использовала исходные переменные окружения и настройки, переданные при запуске командной строки.
Запуск в свернутом или развернутом окне (/MIN, /MAX)
Параметры /MIN и /MAX позволяют управлять состоянием окна запущенной программы:
START /MIN программа.exe START /MAX программа.exe
Использование этих параметров поможет автоматически сокращать пространство на экране, когда нужно запускать программы в фоновом режиме, или, наоборот, сделать работу программы максимизированной для полного использования экрана.
Память для 16-разрядных программ (SEPARATE, SHARED)
Для старых 16-разрядных программ Windows доступны параметры /SEPARATE и /SHARED. Эти параметры управляют использованием области памяти:
START /SEPARATE программа16.exe START /SHARED программа16.exe
Параметр /SEPARATE запускает 16-разрядную программу в отдельной области памяти, а /SHARED — в общей. Эти параметры важны для совместимости с устаревшими приложениями.
Приоритет процесса (LOW, NORMAL, HIGH, REALTIME, ABOVENORMAL, BELOWNORMAL)
Процессы можно запускать с различными уровнями приоритета исполнения:
START /LOW программа.exe START /NORMAL программа.exe START /HIGH программа.exe START /REALTIME программа.exe START /ABOVENORMAL программа.exe START /BELOWNORMAL программа.exe
Каждый уровень приоритета оказывает влияние на то, как операционная система будет распределять вычислительные ресурсы между процессами. Использование этих параметров помогает управлять производительностью системы в зависимости от важности конкретных задач.
Узел NUMA и маска сходства
Параметр /NODE указывает предпочтительный узел NUMA, что может увеличить производительность на многопроцессорных системах. Параметр /AFFINITY позволяет задать маску процессоров, на которых будет выполняться процесс. Эти параметры особенно важны для серверных задач, где необходимо уделить внимание распределению нагрузки:
START /NODE 1 /AFFINITY 0x3 программа.exe
Ожидание завершения процесса
Параметр /WAIT указывает командной строке дождаться завершения запущенного процесса перед продолжением исполнения следующих команд в сценарии:
START /WAIT долгая_операция.exe
Этот параметр полезен для сценариев, где дальнейшее выполнение команды зависит от исхода предыдущей.
Параметры приоритета процесса
Приоритет процесса определяет, сколько времени процессор будет выделять конкретному процессу относительно других запущенных процессов. Установление правильного приоритета может значительно повлиять на производительность вашего приложения.
ABOVENORMAL
Параметр ABOVENORMAL используется для запуска приложения с классом приоритета, который выше стандартного. Это означает, что операционная система будет уделять больше процессорного времени этому приложению по сравнению с процессами с нормальным приоритетом. Это может быть особенно полезно для приложений, требующих большего количества ресурсов процессора.
Пример использования параметра ABOVENORMAL:
start /ABOVENORMAL application.exe
Использование этого класса приоритета может быть полезно для задач, требующих быстрого завершения, таких как рендеринг видео или выполнение сложных вычислительных задач. Однако злоупотребление этим параметром может привести к снижению общей производительности системы, так как процессор будет уделять меньше времени другим запущенным приложениям.
BELOWNORMAL
Параметр BELOWNORMAL, наоборот, указывает операционной системе, что процесс должен получать меньше процессорного времени по сравнению с процессами с нормальным приоритетом. Это полезно для задач, которые могут выполняться в фоновом режиме, не требующих быстрого завершения.
Пример использования параметра BELOWNORMAL:
start /BELOWNORMAL backgroundTask.exe
Использование этого класса приоритета позволяет улучшить отзывчивость системы для других задач, уменьшая влияние фоновых процессов на общую производительность. Например, задачи резервного копирования данных или обновления антивирусных баз могут выполняться с использованием класса приоритета BELOWNORMAL.
Внутренние команды и пакетные файлы
Командная строка Windows (cmd.exe) поддерживает множество внутренних команд, которые можно использовать для выполнения различных задач. Важно правильно различать, когда использовать внутренние команды cmd.exe, пакетные файлы или сторонние программы.
Внутренние команды
В случае, если запускается внутренняя команда cmd.exe или пакетный файл, Windows запускает командную оболочку (cmd.exe) с ключом /K. Это означает, что окно командной строки останется открытым после завершения команды, предоставляя пользователю возможность продолжить работу в этом окне.
Пример запуска внутренней команды:
start cmd /K dir
Пакетные файлы и сторонние программы
Если команда не является внутренней командой cmd.exe или пакетным файлом, Windows запустит соответствующее исполняемое приложение в графическом или текстовом окне, в зависимости от его типа.
Например, запуск текстового редактора в командной строке:
start notepad.exe
Или запуск сторонней программы:
start "C:\Program Files\Software\app.exe"
Понимание различий между внутренними командами, пакетными файлами и сторонними программами помогает эффективно использовать возможности командной строки Windows для автоматизации и управления системой.
Параметры для мультипроцессорных систем
Работа с мультипроцессорными системами требует точной настройки и управления, чтобы эффективно использовать все доступные ресурсы. В этом разделе мы рассмотрим параметры, которые позволяют управлять процессами в системах с несколькими процессорами.
Параметр /NODE
Параметр /NODE позволяет создавать процессы таким образом, чтобы использовать память в системах NUMA. Технология Non-Uniform Memory Access (NUMA) впервые была реализована в процессорах Intel Xeon. Она позволяет организовать память таким образом, чтобы процессоры имели доступ как к своей локальной памяти, так и к памяти других узлов. Это позволяет минимизировать задержки и оптимизировать производительность системы.
Пример использования параметра /NODE:
start /NODE 1 application.exe
В этом примере процесс будет ограничен использованием памяти из узла NUMA 1, что позволяет минимизировать задержки при доступе к памяти и улучшить производительность.
Параметр /AFFINITY
Параметр /AFFINITY позволяет задавать, на каких процессорах будет выполняться приложение. Это полезно для распределения нагрузки между процессорами и обеспечения оптимального использования ресурсов.
Пример использования параметра /AFFINITY:
start /AFFINITY 0x1 application.exe
В этом примере процесс будет выполняться только на первом процессоре. Это может быть полезно для изоляции ресурсоемких приложений и предотвращения их влияния на другие задачи.
Вызов неисполняемых файлов через сопоставление типов
Для вызова неисполняемых файлов через механизм сопоставления типов файлов достаточно ввести имя файла в командной строке. Например, команда:
START MYFILE.TXT
приведет к запуску текстового редактора Notepad с открытием файла MYFILE.TXT. Это достигается за счет использования ассоциаций файлов, настроенных в системе. Сведения о создании подобных сопоставлений из командных файлов приведены в описаниях команд ASSOC и FTYPE.
Команда ASSOC позволяет устанавливать связь между расширением файла и его типом, например:
assoc .txt=txtfile
Команда FTYPE позволяет назначить программу, которая будет использоваться для открытия файлов определенного типа:
ftype txtfile="%SystemRoot%\system32\NOTEPAD.EXE" "%1"
Таким образом, система понимает, что файлы с расширением .txt должны открываться с помощью Notepad.
Обработка графического интерфейса и команды CMD
При запуске приложения с графическим интерфейсом пользователя обработчик команд CMD.EXE не ожидает завершения работы приложения перед возвратом к приглашению командной строки. Это отличается от поведения при запуске приложений из пакетных файлов, где обработчик ждет завершения выполнения команд. Например, запуск текстового редактора командой:
START NOTEPAD
возвращает управление к командной строке сразу после выполнения команды, то есть до закрытия Notepad.
Такое поведение является преимуществом, позволяющим пользователю продолжать работу в командной строке, не дожидаясь завершения всех запущенных приложений. Однако следует учитывать, что при работе с пакетными файлами такое поведение может внести путаницу и сложности.
Заменяемость команды CMD одним из параметров командной строки
При выполнении командной строки, первым элементом которой является текстовая строка «CMD» без расширения имени файла или указания пути, она заменяется значением переменной COMSPEC. Это продиктовано необходимостью предотвращения запуска CMD.EXE из текущей активной папки, если таковая программа там имеется.
Переменная COMSPEC указывает на путь к исполняемому файлу CMD.EXE, определенному в системных настройках. Например, заданный путь может выглядеть следующим образом:
C:\Windows\System32\cmd.exe
Эта переменная гарантирует, что при запуске командной строки используется правильный исполняемый файл CMD.EXE, независимо от текущего каталога, в котором могут находиться другие экземпляры файла с тем же именем.
Использование переменной окружения PATHEXT
Если первый элемент командной строки не содержит расширения имени файла, обработчик команд CMD.EXE использует значение переменной среды PATHEXT, чтобы определить расширения имен исполняемых файлов и порядок поиска нужного файла. По умолчанию для переменной PATHEXT задается значение:
.COM; .EXE; .BAT; .CMD
Таким образом, если вы вводите команду без указания расширения (например, MYAPP вместо MYAPP.EXE), CMD.EXE выполняет поиск исполняемого файла с одним из перечисленных расширений в указанном порядке.
Этот механизм упрощает работу с командной строкой, позволяя пользователю не вводить полные имена файлов и облегчая запуск программ. Например, можно просто ввести:
MYAPP
вместо:
MYAPP.EXE
Управление путями и запуск проводника
Если при поиске исполняемого файла нет соответствия ни одному из расширений, выполняется проверка соответствия указанного имени папки. Если имя папки соответствует указанному пути, то команда START запускает Windows Explorer для открытия данного пути. Это удобно, если вы хотите открыть директорию в проводнике прямо из командной строки.
Примером такой команды может быть:
start C:\windows
Эта команда откроет папку C:\windows в новом окне проводника. Если это действие выполняется из командной строки, оно эквивалентно выполнению команды CD /D для указанного пути.
Использование команды START для открытия папок позволяет гибко управлять файловой структурой прямо из командной строки, что значительно упрощает навигацию и работу с файлами.
Ограничения и совместимость
Поддержка платформ
Важно отметить, что некоторые параметры имеют ограничения по поддержке на различных платформах Windows. Параметры SEPARATE и SHARED не поддерживаются на 64-разрядных платформах. Параметры /NODE и /AFFINITY не поддерживаются в операционной системе Windows Vista и более ранних версиях ОС Windows. Пользователи должны учитывать эти ограничения при планировании автоматизации и настройки своих систем.
Совместимость с версиями Windows
Параметры командной строки имеют разную совместимость с версиями Windows. Современные версии Windows, начиная с Windows 7 и выше, поддерживают большинство параметров, указанных в данной статье. Однако в более ранних версиях, таких как Windows XP или Windows Vista, функциональность может быть ограничена. Перед использованием этих параметров рекомендуется проверить соответствующую документацию для конкретной версии операционной системы.
Рассмотрим несколько практических примеров, которые иллюстрируют использование команды START в реальных сценариях.
Пример 1: Запуск в свернутом состоянии
Предположим, нужно запустить текстовый редактор в свернутом состоянии, чтобы он не мешал основной рабочей среде:
START /MIN notepad.exe
В результате текстовый редактор Notepad будет запущен, но не займет место на экране.
Пример 2: Указание рабочей директории
Запустим программу, которая зависит от файлов в определенной директории:
START /D "C:\MyApp" myapp.exe
Эта команда запустит программу myapp.exe, расположенную в каталоге C:\MyApp, и установит этот каталог в качестве рабочего.
Пример 3: Высокий приоритет выполнения
Запуск ресурсоемкой программы с высоким приоритетом для быстрого выполнения:
START /HIGH heavyapp.exe
Эта команда обеспечит программе heavyapp.exe максимальный доступ к системным ресурсам.
Пример 4: Ограничение процессорами
Запуск программы с ограничением на использование конкретных процессоров:
START /AFFINITY 0x1 myapp.exe
В данном примере программа myapp.exe будет выполняться только на первом процессоре (бит 0x1).
Пример 5: Запуск приложения без создания нового окна
Если необходимо запустить приложение без создания нового окна и отключить обработку сочетания клавиш CTRL+C, используется параметр /B. Это помогает предотвратить прерывание приложений:
START /B моя_программа.exe
Пример 6: Оптимизация производительности приложения
Рассмотрим пример, когда требуется улучшить производительность ресурсоемкого приложения. Запуск приложения с классом приоритета ABOVENORMAL позволит максимально использовать доступные ресурсы процессора, минимизируя время выполнения задачи.
start /ABOVENORMAL videoRenderer.exe
В данном случае приложение для рендеринга видео запустится с приоритетом выше стандартного, что позволит сократить время на обработку видеофайла.
Пример 7: Уменьшение влияния фоновых задач
Если существуют фоновые задачи, такие как резервное копирование данных, которые не требуют быстрого завершения, можно использовать параметр BELOWNORMAL, чтобы снизить их влияние на производительность системы.
start /BELOWNORMAL backupTask.exe
Этот пример показывает, как можно запускать резервное копирование данных с пониженным приоритетом, оставляя основные ресурсы для других более важных задач.
Пример 8: Управление процессами на мультипроцессорной системе
Для оптимизации работы на системе с архитектурой NUMA можно использовать параметр /NODE, чтобы процесс использовал память из конкретного узла.
start /NODE 1 databaseServer.exe
В этом случае сервер базы данных будет выполнять операции с памятью из узла NUMA 1, что минимизирует задержки и повышает производительность.
Также можно использовать параметр /AFFINITY для распределения процесса по конкретным процессорам:
start /AFFINITY 0x2 analyticsTool.exe
Этот пример показывает, как инструмент анализа данных будет выполняться только на втором процессоре, что позволяет избежать влияния на другие задачи, выполняющиеся на других процессорах.
Рекомендации по использованию команды START
При использовании команды START важно учитывать следующие рекомендации:
- Проверка параметров: Убедитесь, что параметры указаны корректно, так как неверные параметры могут привести к неправильному поведению или сбоям в работе системы.
- Совместимость программ: При запуске старых программ с параметрами
/SEPARATEи/SHAREDубедитесь, что система поддерживает 16-разрядные программы. - Приоритеты процессов: Указывайте приоритеты процессов с осторожностью, так как высокие приоритеты могут негативно повлиять на работу других процессов.
- Ожидание завершения: Используйте параметр
/WAIT, когда необходимо дождаться завершения одного процесса перед началом другого. Это особенно важно в сценариях автоматизации. - Рабочие каталоги: Убедитесь, что указанный рабочий каталог существует и доступен, чтобы избежать ошибок при запуске.
Заключение
Команда START в Windows Command Prompt – мощный инструмент для запуска программ и команд с различными настройками и параметрами. Ее гибкость и функциональность делают ее важной частью инструментов системного администратора и разработчика. Понимание всех возможностей команды START позволяет эффективно управлять процессами, устанавливая приоритеты, задавая категории объектов памяти, работая с многопроцессорными системами и управляя окнами командной строки. Благодаря этим характеристикам, команда START остается одним из наиболее полезных инструментов в арсенале опытного пользователя Windows.
