-
Method 1: Using Start Command
-
Method 2: Using a VBS Script
-
Method 3: Using PowerShell
-
Conclusion
-
FAQ
Are you looking to streamline your workflow when using Batch Scripts? If you’ve ever opened a program through a Batch Script and found yourself staring at the console window, you’re not alone. Many users want to run applications without the command prompt lingering in the background. Fortunately, there are effective methods to close the console automatically after launching a program.
In this tutorial, we’ll explore simple yet powerful techniques to achieve this, allowing you to enhance your Batch Script experience. Whether you’re a beginner or an experienced programmer, you’ll find these methods easy to implement. Let’s dive in!
Method 1: Using Start Command
One of the simplest ways to open a program in a Batch Script and close the console immediately is by using the start
command. This command allows you to start a program in a new window, which means the original console window can close right after the command is executed.
Here’s how you can do it:
@echo off
start "" "C:\Path\To\Your\Program.exe"
exit
Output:
Program launched and console closed.
In this example, we start with @echo off
to prevent commands from being displayed in the console. The start
command is used to launch the program, with an empty title argument (""
) to avoid any issues. After the program is launched, the exit
command closes the console window immediately. This method is straightforward and effective, making it ideal for users who want a quick solution without diving into more complex scripting.
Method 2: Using a VBS Script
If you want to take a different approach, using a Visual Basic Script (VBS) can be an excellent option. This method involves creating a small VBS file that runs your Batch Script and then closes the console window. This is particularly useful if you want to maintain a clean user experience.
Here’s how to set it up:
- Create a new text file and save it with a
.vbs
extension, for example,launch.vbs
. - Insert the following code into the VBS file:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "C:\Path\To\Your\BatchScript.bat", 0, False
Output:
Batch script executed and console closed.
In this code, we create an instance of the WScript.Shell
object, which allows us to run the Batch Script. The Run
method is called with three parameters: the path to the Batch Script, a 0
to indicate that the console should not be visible, and False
to allow the script to run asynchronously. This means that the console window will not appear at all, providing a seamless experience. This method is particularly beneficial for scenarios where you want to run scripts in the background without user intervention.
Method 3: Using PowerShell
For those who prefer PowerShell, you can also achieve this functionality by invoking your Batch Script through a PowerShell command. This method is slightly more advanced but offers great flexibility.
Here’s how to implement it:
Start-Process "C:\Path\To\Your\BatchScript.bat" -WindowStyle Hidden
Output:
Batch script executed with hidden console.
In this PowerShell command, Start-Process
is utilized to run the Batch Script. The -WindowStyle Hidden
parameter ensures that no console window appears when the script is executed. This is particularly useful for automating tasks where user interaction is not required. By using PowerShell, you can integrate more complex logic and control over how your scripts are executed, making it a powerful tool in your scripting arsenal.
Conclusion
Closing the console window after opening a program in a Batch Script can significantly enhance your workflow, providing a cleaner and more efficient user experience. Whether you choose to use the start
command, a VBS script, or PowerShell, each method offers its own advantages. By implementing these techniques, you can streamline your processes and focus on what really matters—getting things done. So go ahead, try out these methods, and enjoy a more polished scripting experience!
FAQ
-
How do I create a Batch Script?
You can create a Batch Script by opening a text editor like Notepad, writing your commands, and saving the file with a.bat
extension. -
Can I run multiple programs at once using these methods?
Yes, you can chain commands in your Batch Script or create separate VBS or PowerShell scripts for each program you want to run. -
Is it possible to reopen the console after it has been closed?
Yes, you can manually open a new command prompt window or create a separate Batch Script to do so. -
What if my program requires administrative privileges?
You may need to run your Batch Script or PowerShell script as an administrator to ensure the program has the necessary permissions.
- Are there any limitations to using VBS for this task?
VBS scripts may not be supported on all systems or may require specific configurations, but they are generally effective for hiding console windows.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Get the CMD.exe Window to close
Do you ever have a bat or cmd file that you have written to do something like update a config file then launch a application or process, and have it fail to close the cmd window after it completes even with the “EXIT” command placed at the end of script?
Yes? Funny… me too.
Here is what I found fixes the issue.
I have a script that updates the desktop gadgets your profile should launch upon login. Pretty simple script, it copies the settings.ini file from a network share and places it in your profile directory under “sidebar” and then launches sidebar.exe with a switch. This is a great script for controlling the gadgets seen on a users desktop. (Script example below if you want it)
The problem I was having with this script was I was trying to launch the sidebar application after the update and that was causing the cmd window not to close after it launched the application.
C:\Program Files\Windows Sidebar\sidebar.exe” /autostart
Here is the trick to get a cmd that fails to release after launch in a batch file to actually release.
start “” “C:\Program Files\Windows Sidebar\sidebar.exe” /autostart
If you look at the command, I use the “start” cmd and then supply (“”) a literal nothing as a switch to the “start” cmd. Then in quotes (if spaces exist) the command to run.
Wow, the window now closes after it launches the sidebar application.
I hope this helps some scripter out there with login scripts they are writing. Below you will find a copy of my login script to set gadgets up on Desktop when a user logs in.
Here is a little more about the “load default gadgets at login” script.
[Force default gadgets to load on the desktop when a user logs in]
How to force default gadgets on a users desktop, First off to get started you need to setup a profile and launch the gadgets you want on the desktop. Move them where you want them to be on the desktop so that they are placed in the areas you want them. We have dual monitors across our tech team so we placed all gadgets on second monitor.
Now go grab the config file you just created by moving and launching the gadgets you wanted. The default location for the gadget config file in a users profile is:
%userprofile%\AppData\Local\Microsoft\Windows Sidebar\Settings.ini
Lastly we create a batch file to recopy this file each time a user logs in and then launches the sidebar application.
Create a new batch file called gadgets.bat then place the following in the file.
REM @echo off
taskkill /IM sidebar.exe /f
copy /Z /Y \\myserver\myshare\Settings.ini “%userprofile%\AppData\Local\Microsoft\Windows Sidebar\”
start “” “C:\Program Files\Windows Sidebar\sidebar.exe” /autostart
Copy the Settings.ini file to a network share. Edit the “myserver” and the “myshare” to represent your network share that holds the “Settings.ini” file.
Then add it to your users login script active directory properties. You can also just copy and paste the lines in to an existing login script if your using them to do other things like mapping drives or printers and such.
Download script -> Launch Default Gadgets batch file
or How to close batch files
Even our favorite batch files will, at some time, need to quit.
Sometimes they need to quit based on a condition that has been or has not been met.
And every batch file needs to quit, and will do so, when it reaches the last line of code.
There are several ways to end batch file execution, like reaching the end of the batch file, starting execution of another batch file, or using the EXIT
or GOTO:EOF
commands.
Each operating system may react in its own way to any of these events.
And often there is a difference between ending batch file execution and closing the batch file’s console (window).
Reaching the end
After the batch file has executed its last line of code it will stop running, unless the last line contained a GOTO
command forcing it to re-execute some of its previous code.
When the batch file stops running it will return control to the command processor.
If that command processor was started just for the purpose of executing the batch file, the command processor itself will stop running after completing batch file execution.
This may be the case when a batch file is started by double-clicking a shortcut in Windows or OS/2.
Though the batch file may be terminated, the console (window) the batch file has been running in may be left open, depending on the operating system, the command processor, and how batch file execution was started (from a command prompt or through a shortcut).
Operating System | Command Processor | Command Prompt | Shortcut | CALLed subroutine | Remarks |
---|---|---|---|---|---|
MS-DOS 3…6.22 | COMMAND.COM | Leave command prompt open | N/A | N/A | |
MS-DOS 7.* (Windows 9x) | COMMAND.COM | Leave command prompt open | Leave console window open | N/A | Make sure no text is displayed in the console window to make it close automatically at the end of the batch file |
OS/2 | CMD.EXE | Leave command prompt open | Leave console window open | N/A | |
OS/2 | COMMAND.COM | Leave command prompt open | Leave console window open | N/A | |
Windows NT 4 | CMD.EXE | Leave command prompt open | Close console window | Return to CALLing command line | |
Windows NT 4 | COMMAND.COM | Leave command prompt open | Close console window | N/A | |
Windows 2000/XP/2003 | CMD.EXE | Leave command prompt open | Close console window | Return to CALLing command line | |
Windows 2000/XP/2003 | COMMAND.COM | Leave command prompt open | Close console window | N/A |
EXIT
Using EXIT
will stop execution of a batch file and return control to the command processor (or, with NT’s /B
switch, to the calling batch file) immediately.
Operating System | Command Processor | Command Prompt | Shortcut | CALLed subroutine | Remarks |
---|---|---|---|---|---|
MS-DOS 3…6.22 | COMMAND.COM | Leave command prompt open | N/A | N/A | |
MS-DOS 7.* (Windows 9x) | COMMAND.COM | Close command prompt | Leave console window open | N/A | Make sure no text is displayed in the console window to make it close automatically at the end of the batch file |
OS/2 | CMD.EXE | Close command prompt | Close console window | Close command prompt or window | |
OS/2 | COMMAND.COM | Close command prompt | Close console window | N/A | |
Windows NT 4 | CMD.EXE | Close command prompt | Close console window | Close command prompt or window | |
Windows NT 4 | COMMAND.COM | Close command prompt | Close console window | N/A | |
Windows 2000/XP/2003 | CMD.EXE | Close command prompt | Close console window | Close command prompt or window | |
Windows 2000/XP/2003 | COMMAND.COM | Close command prompt | Close console window | N/A |
EXIT /B n
Using EXIT /B
will stop execution of a batch file or subroutine and return control to the command processor or to the calling batch file or code immediately.
EXIT /B
is available in Windows 2000 and later versions’ CMD.EXE only.
If followed by an integer number the code will return an exit code or ERRORLEVEL equal to that number.
Operating System | Command Processor | Command Prompt | Shortcut | CALLed subroutine | Remarks |
---|---|---|---|---|---|
MS-DOS 3…6.22 | COMMAND.COM | N/A | N/A | N/A | |
MS-DOS 7.* (Windows 9x) | COMMAND.COM | N/A | N/A | N/A | |
OS/2 | CMD.EXE | N/A | N/A | N/A | |
OS/2 | COMMAND.COM | N/A | N/A | N/A | |
Windows NT 4 | CMD.EXE | N/A | N/A | N/A | |
Windows NT 4 | COMMAND.COM | N/A | N/A | N/A | |
Windows 2000/XP/2003 | CMD.EXE | Leave command prompt open | Close console window | Leave subroutine and return to calling code | |
Windows 2000/XP/2003 | COMMAND.COM | N/A | N/A | N/A |
Here is a more detailed explanation by Timothy Dollimore:
The DOS online help (
HELP EXIT
) doesn’t make it clear that the/B
parameter exits the current instance of script which is not necessarily the same as exiting the current script.
I.e. if the script is in a CALLed piece of code, theEXIT /B
exits theCALL
, not the script.To explain, one can use
EXIT /B 0
in a similar fashion toGOTO:EOF
to exit (or more accurately, return) from a called section of code inside a script.
GOTO:EOF
In short, GOTO:EOF
should have the same result as reaching the end of the batch file.
It marks the end of a subroutine, and returns to the CALLing code.
GOTO:EOF
is available in Windows NT 4 and
later versions’ CMD.EXE only.
Operating System | Command Processor | Command Prompt | Shortcut | CALLed subroutine | Remarks |
---|---|---|---|---|---|
MS-DOS 3…6.22 | COMMAND.COM | N/A | N/A | N/A | |
MS-DOS 7.* (Windows 9x) | COMMAND.COM | N/A | N/A | N/A | |
OS/2 | CMD.EXE | N/A | N/A | N/A | |
OS/2 | COMMAND.COM | N/A | N/A | N/A | |
Windows NT 4 | CMD.EXE | Leave command prompt open | Close console window | Leave subroutine and return to calling code | |
Windows NT 4 | COMMAND.COM | N/A | N/A | N/A | |
Windows 2000/XP/2003 | CMD.EXE | Leave command prompt open | Close console window | Leave subroutine and return to calling code | |
Windows 2000/XP/2003 | COMMAND.COM | N/A | N/A | N/A |
page last modified: 2016-09-19; loaded in 0.0021 seconds
Как использовать OAuth2 со Spring Security в Java
Javaican 14.05.2025
Протокол OAuth2 часто путают с механизмами аутентификации, хотя по сути это протокол авторизации. Представьте, что вместо передачи ключей от всего дома вашему другу, который пришёл полить цветы, вы. . .
Анализ текста на Python с NLTK и Spacy
AI_Generated 14.05.2025
NLTK, старожил в мире обработки естественного языка на Python, содержит богатейшую коллекцию алгоритмов и готовых моделей. Эта библиотека отлично подходит для образовательных целей и. . .
Реализация DI в PHP
Jason-Webb 13.05.2025
Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .
Обработка изображений в реальном времени на C# с OpenCV
stackOverflow 13.05.2025
Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .
POCO, ACE, Loki и другие продвинутые C++ библиотеки
NullReferenced 13.05.2025
В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .
Паттерны проектирования GoF на C#
UnmanagedCoder 13.05.2025
Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .
Создаем CLI приложение на Python с Prompt Toolkit
py-thonny 13.05.2025
Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .
Конвейеры ETL с Apache Airflow и Python
AI_Generated 13.05.2025
ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .
Выполнение асинхронных задач в Python с asyncio
py-thonny 12.05.2025
Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .
Работа с gRPC сервисами на C#
UnmanagedCoder 12.05.2025
gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .
Перейти к содержимому раздела
Серый форум
разработка скриптов
Вы не вошли. Пожалуйста, войдите или зарегистрируйтесь.
Страницы 1
Чтобы отправить ответ, вы должны войти или зарегистрироваться
1 2011-07-22 18:53:40 (изменено: SANIOK_AV, 2011-07-22 18:59:32)
- SANIOK_AV
- Участник
- Неактивен
- Рейтинг : [0|0]
Тема: CMD/BAT: Закрыть окно CMD после вызова программы.
Доброго времени суток!
Подскажите пожалуйста как закрыть окно CMD после вызова программы, не дожидаясь закрытия этой программы?
@echo off
choice /m "To run the program?"
if errorlevel 2 goto end
D:\program.exe
:end
Хочу чтобы сразу после запуска program.exe (если я перед этим выбрал «Yes») цмд-шное окно закрылось…
Заранее благодарен!!!
2 Ответ от alexii 2011-07-22 19:56:50
- alexii
- Разработчик
- Неактивен
Re: CMD/BAT: Закрыть окно CMD после вызова программы.
start "" "D:\program.exe"
3 Ответ от SANIOK_AV 2011-07-23 13:06:09
- SANIOK_AV
- Участник
- Неактивен
- Рейтинг : [0|0]
Re: CMD/BAT: Закрыть окно CMD после вызова программы.
alexii, Cпасибо большое!!!
Сообщения 3
Страницы 1
Чтобы отправить ответ, вы должны войти или зарегистрироваться