Bat file start with windows

Команда START — запуск приложения в новом окне

Команда START позволяет запускать приложения в отдельном окне, с возможностью указания некоторых параметров их выполнения.

Формат командной строки:

START [«заголовок»] [/D путь] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | REALTIME| /ABOVENORMAL | /BELOWNORMAL] [/WAIT] [/B] [команда/программа] [параметры]

Параметры командной строки:

«заголовок» — заголовок окна. Обязательно в двойных кавычках.

путь — рабочий каталог.

B — запуск приложения без создания нового окна с отключением обработки сочетания клавиш CTRL+C. Если приложение не обрабатывает сочетание клавиш CTRL+C самостоятельно, единственным способом его прерывания является использование сочетания клавиш CTRL+Break.

I — Новой средой станет исходная среда, переданная cmd.exe, а не текущая среда.

MIN — Запуск команды/программы в свернутом окне.

MAX — Запуск команды/программы в развернутом окне.

SEPARATE — Запуск 16-разрядной программы Windows в отдельной области памяти.

SHARED — Запуск 16-разрядной программы Windows в общей области памяти.

LOW — Запуск приложения с приоритетом IDLE (самый низкий приоритет).

NORMAL — Запуск приложения с приоритетом NORMAL.

HIGH — Запуск приложения с приоритетом HIGH.

REALTIME — Запуск приложения с приоритетом REALTIME (самый высокий приоритет).

WAIT — Запуск приложения с ожиданием его завершения.

ABOVENORMAL — Запуск приложения с классом приоритета ABOVENORMAL (выше стандартного)

BELOWNORMAL — Запуск приложения с классом приоритета BELOWNORMAL (ниже стандартного)

команда/программа — Если это внутренняя команда cmd.exe или пакетный файл, обработчик команд (cmd.exe) запускается с ключом /K. Это означает, что окно не будет закрыто после завершения команды. Если это не внутренняя команда cmd.exe и не пакетный файл, значит, это программа, которая будет запущена в графическом или текстовом окне.

параметры — Параметры, передаваемые команде/программе.

Для вызова неисполняемых файлов через механизм сопоставления типов файлов достаточно просто ввести имя файла в командной строке. Например, команда

приведет к запуску текстового редактора NOTEPAD с открытием файла MYFILE.TXT. Сведения о создании подобных сопоставлений из пакетных файлов приведены в описаниях команд ASSOC и FTYPE.

При запуске 32-разрядного приложения с графическим интерфейсом пользователя обработчик команд CMD.EXE не ожидает завершения работы приложения перед возвратом к приглашению командной строки. Подобное новое поведение НЕ относится к запуску приложений из пакетных файлов.

При выполнении командной строки, первым элементом которой является текстовая строка «CMD» без расширения имени файла или указания пути, она заменяется значением переменной COMSPEC. Это предотвращает запуск CMD.EXE из текущей активной папки, если таковая программа там имеется.

Если первый элемент командной строки не содержит расширения имени файла, обработчик команд CMD.EXE использует значение переменной среды PATHEXT, чтобы определить расширения имен исполняемых файлов и порядок поиска нужного файла. По умолчанию для переменной PATHEXT задается значение:

Обратите внимание, что этот синтаксис подобен синтаксису для переменной PATH, то есть отдельные элементы разделяются точкой с запятой.

Если при поиске исполняемого файла нет соответствия ни одному из расширений, выполняется проверка соответствия указанного имени папки. Если имя папки соответствует указанному, то команда START запускает EXPLORER для этого пути. Если такое действие выполняется из командной строки, то оно эквивалентно выполнению команды CD /D для указанного пути. Так, например, команда

откроет папку C:\windows в окне проводника.

start /? — выдать справку об использовании команды.

start — при запуске без параметров будет открыто новое окно интерпретатора команд CMD.

start «My new CMD window» — как и в предыдущем случае, выполнится запуск CMD в новом окне, но в качестве заголовка окна будет отображаться текст My new CMD window

start devmgmt.msc — выполнится запуск по расширению .msc диспетчера устройств Windows.

start http://google.com — выполнится запуск обозревателя Интернет и откроется страница поисковика Google.

start mailto:test@mail.ru — выполнится запуск почтового клиента в режиме подготовки электронного письма для адреса test@mail.ru .

start /min notepad.exe — выполнится запуск блокнота в свернутом окне.

start «Backup Files» /min /belownormal mybackup.bat — запуск командного файла в свернутом окне с пониженным приоритетом.

Читайте также:  Пропадает высокоскоростное подключение windows 10

start /abovenormal /MAX winword.exe — запуск редактора Microsoft Word в новом окне, развернутом на весь экран и с повышенным приоритетом.

start «» /high /MAX «C:\Program Files\Good game\MyGame» — запуск программы MyGame с высоким приоритетом.

Управление приоритетами удобно использовать для обеспечения комфортной работы пользователя с интерактивными приложениями на фоне выполнения длительных расчетных задач. Так, например равных приоритетах редактора MS Word, и расчетной задачи, потребляющей значительную долю ресурсов центрального процессора, может возникнуть эффект подвисаний при работе с текстовым документом. Снижение же приоритета расчетной задачи создаст нормальные условия для работы пользователя на фоне ее работы.

Обратите внимание на то что заголовок окна можно опускать, но особенность обработки входных параметров командой start может привести к неожиданным результатам при попытке запуска программы, имя или путь которой содержит пробел(ы). Например, при попытке выполнить следующую команду:

How to create and run batch file on Windows 10

Source: Windows Central

On Windows 10, a batch file is a special text file that typically has a .bat extension, and it includes one or more commands that Command Prompt can understand and run in sequence to perform various actions.

Usually, you can type commands manually to perform a particular task or change system settings on Windows 10. However, a batch file simplifies the work of retyping commands, saving you time and potentially irreversible mistakes.

You can also use other tools like PowerShell to write even more advanced scripts. However, using batch files with Command Prompt is a convenient option when you need to run commands to change settings, automate routines, and start apps or launch websites.

In this Windows 10 guide, we’ll walk you through the steps to create and run your first batch file on your device. Also, we’ll outline the steps to create advanced scripts and automate scripts using the Task Scheduler.

How to create a batch file on Windows 10

The process of creating a batch (script or batch script) file is simple. You only need a text editor and some basic knowledge typing Command Prompt native commands. In the instructions below, we’ll outline the steps for writing a basic and advanced batch file, as well as the steps to write a script to change the system settings on Windows 10.

Create basic batch file

To create a basic batch file on Windows 10, use these steps:

  1. Open Start.
  2. Search for Notepad and click the top result to open the app.

Type the following lines in the text file to create a batch file:

Source: Windows Central

The above script outputs the phrase, «Congratulations! Your first batch file executed successfully» on the terminal screen.

Source: Windows Central

  • @ECHO OFF — Disables the display prompt to show only the message on a clean line. Usually, this line goes at the beginning of the file. (You can use this command without «@,» but the symbol hides the command being executed to create a cleaner return.)
  • ECHO — Prints any text on the screen.
  • PAUSE — Keeps the window open after executing the command. If you don’t use this command, the window will close automatically as soon as the script finishes running. You can use this command at the end of the script or after a specific command when running multiple tasks, and you want to pause between them.
  • Click the File menu.
  • Select the Save as option.

    Type a name for the script — for example, first_basic_batch.bat.

    Quick note: While batch files typically use the .bat file extensions, you can also find scripts using the .cmd or .btm file extensions.

    Once you complete the steps, you can double-click the file to run it, or you can use the steps below to learn the different ways to execute a batch file on Windows 10.

    Create advanced batch file

    To create an advanced batch file to execute multiple commands, use these steps:

    1. Open Start.
    2. Search for Notepad and click the top result to open the app.

    Type the following lines in the text file to create a more advanced batch file:

    Source: Windows Central

    The above script runs a series of commands to query different system information. Then it groups them into three different categories, including «WINDOWS INFO,» «HARDWARE INFO,» and «NETWORK INFO.» The «start» command will also open a Microsoft support website listing the official Windows 10 system requirements on your default web browser, which you can check against your information.

    Source: Windows Central

    • @ECHO OFF — Disables the display prompt to show only the message on a clean line. Usually, this line goes at the beginning of the file. (You can use this command without «@,» but the symbol hides the command being executed for a cleaner return.)
    • TITLE — Displays a custom name in the title bar of the window.
    • :: — Allows you to write comments and documentation information. These details are ignored when the batch file runs.
    • ECHO — Prints the exact text on the screen.
    • START — Lets you launch an app or website with the default web browser.
    • PAUSE — Keeps the window open after executing the command. If you don’t use this command, the window will close automatically as soon as the script finishes running. You can use this command at the end of the script or after a specific command when running multiple tasks, and you want to pause between them.
  • Click the File menu.
  • Select the Save as option.
  • Type a name for the script — for example, first_advanced_batch.bat.
  • After you complete the steps, double-click the .bat file to run it, or you can use the steps below to learn the different ways to run a batch.

    Create actionable batch file

    In addition to executing and displaying content in a Command Prompt window, you can also write non-interactive batch scripts to perform virtually any task you need.

    To create a batch file that runs a specific command without user interaction, use these steps:

    1. Open Start.
    2. Search for Notepad and click the top result to open the app.

    Copy and paste the following command in the text file:

    Source: Windows Central

    Quick note: In the screenshot, you’ll notice the «pause» command, but it’s not required. It was added in this example to take a screenshot of the terminal. If you’re accessing the files from another computer that uses a specific username and password, don’t forget to use the /user: option with the necessary credentials.

    The above script includes a simple command to map a network folder as a drive inside File Explorer using the «Z» drive letter.

    Source: Windows Central

  • Click the File menu.
  • Select the Save as option.
  • Type a name for the script — for example, mount-z-network-drive.bat.
  • Once you complete the steps, the batch file will map the network folder with the specified settings without opening a Command Prompt window. While we only used one command in this particular file, you can include as many commands as you like, as long as you write them one per line.

    How to run a batch file on Windows 10

    On Windows 10, you can run a batch file in at least three ways. You can run it on-demand using File Explorer or Command Prompt. You can create a task with Task Scheduler to run it on schedule. Or you can place the script in the «Startup» folder to run it every time you sign in to your Windows 10 account.

    Run batch file on-demand

    If you need to run a script on-demand, you have two choices, including Command Prompt or File Explorer.

    Command Prompt

    To run a batch file with Command Prompt, use these steps.

    1. Open Start.
    2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.

    Type the path and name of the batch file, and press Enter:

    For example, the following command runs the batch file located in the «scripts» folder, inside the «Downloads» folder:

    Source: Windows Central

    After you complete the steps, the console will return the results, and the window won’t close even if the script doesn’t include the «PAUSE» command.

    File Explorer

    To run a batch file with File Explorer, use these steps:

    1. Open File Explorer.
    2. Browse to the folder with the script.
    3. Double-click the batch file to run it.

    (Optional) If you execute a command that requires administrator privileges, you’ll need to run the script as an admin by right-clicking the batch file and selecting the Run as administrator option.

    Source: Windows Central

  • Click the Yes button
  • Once you complete the steps, the batch will run each command in sequence displaying the results in the terminal.

    Run batch file on schedule

    To schedule a batch file on Windows 10, you can use the Task Scheduler with these steps:

    1. Open Start.
    2. Search for Task Scheduler and click the top result to open the app.
    3. Right-click the «Task Scheduler Library» branch and select the New Folder option.

    Type a name for the folder — for example, MyScripts.

    Quick note: It’s not a requirement to create a folder, but it’s recommended to keep tasks organized.

    Select the Create Basic Task option.

    Source: Windows Central

    In the «Name» field, type a descriptive name for the task — for example, SystemInfoBatch.

    Source: Windows Central

    Select the Monthly option.

    Source: Windows Central

    Quick note: On Windows 10, the Task Scheduler allows you to choose from different triggers, including a specific date, during startup, or when a user signs in to the device. In this case, we’re selecting the option to run a task every month, but you may need to configure additional parameters depending on your requirements.

    Use the «Monthly» drop-down menu to pick the months of the year you want to run the task.

    Source: Windows Central

    Use the «Days» or «On» drop-down menu to confirm the days the task will run.

    Source: Windows Central

    Select the Start a program option to run the batch file.

    Source: Windows Central

    Select the batch file you created.

    Source: Windows Central

  • Click the Finish button.
  • Once you complete the steps, the task will save and run the script on a schedule.

    These instructions cover the steps to create a basic task with Task Scheduler. If you want to create a more customizable task, use these instructions.

    Run batch files on startup

    If you want to execute a sequent of commands every time you sign in to your Windows 10 account, instead of using Task Scheduler, you can place the script in the «startup» folder to save the extra steps.

    To run a script on startup on Windows 10, use these easy steps:

    1. Open File Explorer.
    2. Browse to the folder with the batch file.
    3. Right-click the batch file and select the Copy option.
    4. Use the Windows key + R keyboard shortcut to open the Run command.

    Type the following command:

    Source: Windows Central

    Click the Paste option from the «Home» tab in the Startup folder. (Or Click the Paste shortcut button to create a shortcut to the batch file.)

    Source: Windows Central

  • Sign out of your account.
  • Sign back into the account.
  • After you complete the steps, every time you sign in to Windows 10, the batch file will execute and run the included commands.

    We’re focusing this guide on Windows 10, but the ability to run batch files has been around for a long time, which means that you can refer to these instructions if you are still on an older version, including Windows 8.1 or Windows 7.

    More Windows 10 resources

    For more helpful articles, coverage, and answers to common questions about Windows 10, visit the following resources:

    Halo: MCC’s live service elements make it better, not worse

    Halo: The Master Chief Collection is more popular than ever, but some fans don’t agree with the live service approach 343 Industries has taken with it. Here’s why those elements are, at the end of the day, great for the game and for Halo overall.

    Microsoft’s Surface Duo is not ‘failing up’

    Microsoft announced this week that it was expanding Surface Duo availability to nine new commercial markets. While Surface Duo is undoubtedly a work in progress, this is not a sign of a disaster. It’s also doesn’t mean that Surface Duo is selling a ton either. Instead, the reason for the expansion is a lot more straightforward.

    Here’s what you can do if Windows 10 update KB5001330 is causing issues

    In this guide, we’ll show you the steps to get rid of the update KB5001330 to fix profile, gaming, and BSoD problems with the Windows 10 October 2020 Update and May 2020 Update.

    These are the best PC sticks when you’re on the move

    Instant computer — just add a screen. That’s the general idea behind the ultra-portable PC, but it can be hard to know which one you want. Relax, we have you covered!

    Читайте также:  Как разгрузить систему windows
    Оцените статью