Windows bat hide console

Rob van der Woude's Scripting Pages

If we run a batch file by starting it manually, we usually don’t mind seeing the «black square» of the console window.
If, on the other hand, we run a batch file scheduled, or remotely, we often would prefer not to see the «black square» at all.

Several tools and techniques exist to hide a console window.

Start a batch file minimized

The most simple solution is to run the batch file minimized.
The batch file will still be visible in the task bar while running.
For batch file started by a shortcut, this may be «sufficiently hidden».

START /MIN "your title" "d:\path\yourbatch.bat"

See this JSIFaq tip on how to make a batch file start another batch file hidden (uses a temporary VBScript file).
Note that, because the script is created and called by a batch file, there will still be a visible console window.

Or download and use my RunNHide.vbs or RunNHide.exe.

Make a batch file minimize its own console

Use one of the following commands within a batch file to minimize that batch file’s console window:

CONSOLESTATE /Min

or:

SETCONSOLE /minimize

or:

TITLE MinimizeMePlease
FOR /F %%A IN ('CMDOW ˆ| FIND "MinimizeMePlease"') DO CMDOW %%A /MIN

Make a batch file hide its own console

Use one of the following commands within a batch file to hide that batch file’s console window:

CONSOLESTATE /Hide

or:

SETCONSOLE /hide

or:

TITLE HideMePlease
FOR /F %%A IN ('CMDOW ˆ| FIND "HideMePlease"') DO CMDOW %%A /HID

or, using KiXtart:

> Temp.kix ECHO SetConsoleˆ("Hide"ˆ)
KIX32.EXE Temp.kix
DEL Temp.kix

Spoiler alert: completely hiding the console is not possible in the standard command interpreters CMD.EXE or COMMAND.COM.
All techniques to hide the console that have to be called from within the batch file will always show at least a short «black flash» of the console being opened before it is hidden.
Therefore, the «cloaking» of the console has to be started before starting the batch file, which means using an alternative scripting language to start the command interpreter hidden.

To restore console visibility, use:

CONSOLESTATE /Show

or:

SETCONSOLE /show

or:

TITLE HideMePlease
FOR /F %%A IN ('CMDOW ˆ| FIND "HideMePlease"') DO CMDOW %%A /VIS

or, using KiXtart:

> Temp.kix ECHO SetConsoleˆ("Show"ˆ)
KIX32.EXE Temp.kix
DEL Temp.kix

Start a batch file minimized

If a console window is visible already, but you want to start another batch file minimized, use one of the following commands:

START /MIN d:\path\yourbatch.bat

or:

CMDOW.EXE /RUN /MIN d:\path\yourbatch.bat

Start a batch file hidden

If a console window is visible already, but you want to start another batch file hidden, use one of the following commands:

PSEXEC -d CMD.EXE /C d:\path\yourbatch.bat

or:

CMDOW.EXE /RUN /HID d:\path\yourbatch.bat

Run a batch file completely hidden

To completely hide the console, a Windows (GUI) executable or an alternative scripting language with GUI based interpreter (e.g. VBScript with WSCRIPT.EXE) has to be used.
Do not use the following commands in a batch file, as this batch file will run in a (visible) console window itself.

RUNNHIDE.EXE d:\path\yourbatch.bat

or:

WSCRIPT.EXE RunNHide.vbs d:\path\yourbatch.bat

or:

HSTART.EXE /NOCONSOLE "d:\some dir\yourbatch.bat"

Make sure the batch file closes its own window in all circumstances, because you won’t be able to see whether it does close or keep running «forever».

Note: CMDOW, HSTART and PSEXEC may sometimes be (wrongly) accused of being malware by some Anti-Virus and malware scanners.
They are not, but they certainly could be abused for «less honorouble» purposes.

page last modified: 2018-12-12; loaded in 0.0013 seconds

Распределенное обучение с TensorFlow и Python

AI_Generated 05.05.2025

В машинном обучении размер имеет значение. С ростом сложности моделей и объема данных одиночный процессор или даже мощная видеокарта уже не справляются с задачей обучения за разумное время. Когда. . .

CRUD API на C# и GraphQL

stackOverflow 05.05.2025

В бэкенд-разработке постоянно возникают новые технологии, призванные решить актуальные проблемы и упростить жизнь программистам. Одной из таких технологий стал GraphQL — язык запросов для API,. . .

Распознавание голоса и речи на C#

UnmanagedCoder 05.05.2025

Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .

Реализация своих итераторов в C++

NullReferenced 05.05.2025

Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .

Разработка собственного фреймворка для тестирования в C#

UnmanagedCoder 04.05.2025

C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .

Распределенная трассировка в Java с помощью OpenTelemetry

Javaican 04.05.2025

Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .

Шаблоны обнаружения сервисов в Kubernetes

Mr. Docker 04.05.2025

Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .

Создаем SPA на C# и Blazor

stackOverflow 04.05.2025

Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .

Реализация шаблонов проектирования GoF на C++

NullReferenced 04.05.2025

«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .

C# и сети: Сокеты, gRPC и SignalR

UnmanagedCoder 04.05.2025

Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .

Материал из OSZone.net wiki.

Перейти к: навигация, поиск

Для скрытия консольных окон (bat и cmd файлов) есть несколько утилит.

Содержание

  • 1 Утилита cmdow
    • 1.1 Выполнение отдельной команды
  • 2 Утилита hidcon
  • 3 Утилита hidec
  • 4 Утилиты hidecon и hideexec
  • 5 Утилита Nircmd
  • 6 Утилита CHP (Create Hidden Process)
  • 7 Утилита Hstart (Hidden Start)
  • 8 Утилита от Northcode Inc.

Утилита cmdow

Для скрытия консольного окна в пакетном файле должна быть следующая строка:

cmdow @ /HID

Если строка является первой, то окно будет скрыто сразу, но мигнет на долю секунды. Если строка находится в середине, то окно будет скрыто после обработки команд предшествующих cmdow @ /HID.

Скрытие окна — не единственная функция утилиты. Подробнее читайте в статье на Компьютерра-онлайн.

Домашняя странице программы

Выполнение отдельной команды

Основано на сообщении amel27 в форуме автоустановки.

Иногда требуется скрыть выполнение отдельной команды и нет возможности (или не хочется) создавать отдельный .bat или .cmd файл (например при динамическом добавлении в ветку реестра RunOnce). В этом случае можно воспользоваться следующим синтаксисом:

CMD /C (<Путь>cmdow @ /HID) & (<Консольная команда>)

CMD /C (%windir%\Bin\cmdow @ /HID)&(7za.exe x -y -aoa Far1705.7z -o"%ProgramFiles%")

Утилита hidcon

В командной строке указывается имя исполняемого файла и его командная строка. Например,

hidcon.exe adduser.cmd username password

запустит в скрытой консоли adduser.cmd передав ему в качестве первого параметра username, в качестве второго — password.

Автор — Oleg_Sch. Скачать утилиту можно из web-архива или с Яндекса (зеркало).

Утилита hidec

Сходна с hidcon.

hidec.exe [/W] <path>\batch.cmd

Ключ /W (не чувствителен к регистру) заставляет дожидаться окончания отработки пакетного файла. Например,

hidec.exe /W %systemdrive%\install\prepare.cmd
hidec.exe %systemdrive%\install\cleanup.cmd

скрытно запустит prepare.cmd, дождется окончания его отработки и запустит cleanup.cmd.

Обсуждение утилиты на OSZone (авторы там же ;-).
Скачать утилиту .

Утилиты hidecon и hideexec

hidecon — tool to hide the current console (for use by batch files).
hideexec — tool to launch a hidden process; useful for starting console processes silently.

Каждый из архивов содержит x86 и x64 версии, а также исходный код.

Автор — Kai Liu.

Утилита Nircmd

nircmd.exe execmd [command]

где [command] — консольная команда, в том числе и командный файл (фактически происходит запуск %comspec% /c [command] в скрытой консоли).

Примеры

nircmd.exe execmd md с:\temp\folder01
nircmd.exe execmd сacls.exe c:\temp > c:\cacls.txt
nircmd.exe execmd "%ProgramFiles%\My Scripts\Rescan Devices.cmd"

Утилита CHP (Create Hidden Process)

Примеры

CHP notepad <-- runs notepad.exe in a hidden window
CHP notepad /p "New Text Document.txt" <-- silently prints a text file
CHP cmd.exe /c ""d:\my batch file.cmd" arg1 "arg two"" <-- runs a batch file in a hidden window

Утилита Hstart (Hidden Start)

Примеры

hstart /NOCONSOLE "batch_file_1.bat" "batch_file_2.bat" "batch_file_3.bat"

Утилита от Northcode Inc.

Достаточно назвать proxy.exe так же, как и bat\cmd, который вы запускаете, и разместить их в одной директории.

Прямая ссылка

If you’re tired of that black command prompt window popping up every time you run a batch file, you’re not alone.

Whether you’re automating tasks, running scripts in the background, or just want things to look cleaner, there are ways to hide the CMD window.

Here’s how you do it.

Hide CMD Window when Running Batch File

1. Use Slimm Bat To Exe Converter

To create an executable from a batch file without a visible console window:

  1. Click the Windowless Express button.
  2. Browse for your batch script.
  3. The tool will generate an EXE file in the same location as the batch file.

For customization, use the Custom button, which includes an integrated editor and an option to add a custom icon via Tools > Options.

Download Slimm Bat To Exe Converter

2. Convert a Batch File Without Extra Software

Windows includes a built-in tool called IExpress, available since Windows 2000. While primarily designed for creating installation packages, it can also convert a single batch file into an EXE.

2. Convert a Batch File Using IExpress

Instead of manually going through the IExpress Wizard, follow these steps:

  1. Download the pre-made script below.
  2. Extract the ZIP file.
  3. Drag and drop your batch file onto the extracted script.
  4. It will create an executable in the same location as the batch file.
IExpress Wizard

One thing to keep in mind: any files created by your script will end up in %TEMP% and get deleted after execution unless you specify another location.

Download bat2exeIEXP

3. Create an EXE Using AutoIt

Another way to convert a batch file into an EXE is by writing and compiling a script using AutoIt.

Basic AutoIt Script to Run a Batch File Silently

Below is a simple AutoIt script that runs a batch file in the background:

autoitCopyEdit#RequireAdmin
#AutoIt3Wrapper_UseUpx=y
FileInstall("MyBatchFile.bat", @TempDir & "\MyBatchFile.bat", 1)
Run(@ComSpec & " /c " & @TempDir & "\MyBatchFile.bat", "", @SW_HIDE)
  • Line 1 requests admin privileges (optional).
  • Line 2 compresses the EXE (optional).
  • Line 3 embeds the batch file inside the EXE and extracts it to %TEMP%.
  • Line 4 runs the batch file silently without a console window.

For a batch file stored permanently on your PC, you can simplify it to:

autoitCopyEditRun(@ComSpec & " /c " & "C:\Scripts\MyBatchFile.bat", "", @SW_HIDE)

Compiling the Script into an EXE

  1. Install AutoIt (or use the portable version).
  2. Write your AutoIt script and save it as .au3.
  3. Press F7 to compile it into an EXE.

Download AutoIt

Run Silent Batch AutoIt

4. Run a Batch File Silently Using Task Scheduler

Windows Task Scheduler can execute a batch file in the background without third-party tools. This method is ideal for scripts that run on startup, login, or specific schedules.

Creating a Silent Scheduled Task

  1. Open Task Scheduler (Search “Task Scheduler” in Start).
  2. Click Create Basic Task, name it, and click Next.
  3. Select when you want the task to run and click Next.
  4. Choose Start a program, then browse for the batch file.
  5. Check Open properties dialog before clicking Finish.
Create Basic Task

5. Adjusting Task Properties

  1. In the Properties window:
    • Select Run whether user is logged on or not (you may need to enter your password).
    • If your script needs admin rights, check Run with highest privileges.
  2. Click OK to save changes.
Run Whether User Is Logged On or Not

6. Run a Scheduled Task On Demand

To manually run the scheduled task anytime, create a desktop shortcut:

  1. Right-click the desktop > New > Shortcut.
  2. Enter the following command:shCopyEditSchtasks.exe /Run /TN "Task Name"
  3. Replace "Task Name" with the name of your scheduled task.
  4. Click Next, name the shortcut, and click Finish.
Create Scheduled Tasks Shortcut

Tip: If you only want to run the task manually, delete all triggers in the Triggers tab of Task Scheduler.

Why Hide a Batch File?

There are plenty of reasons to run a batch file without showing the CMD window:

  • Prevent Interference: If your script is handling something important, you don’t want someone accidentally closing it.
  • Security & Privacy: Some scripts involve sensitive data—like login credentials or network settings. Keeping the command window hidden helps avoid prying eyes.
  • A Better User Experience: If you’ve got an automated process running, you don’t want a flashing command window stealing focus or cluttering the screen.
  • Bypass Restrictions: In some locked-down environments, IT policies restrict command prompt use. Running your script invisibly keeps things moving without unnecessary roadblocks.
  • Avoid Accidental Termination: The moment someone sees a CMD window, their first instinct is to close it. Running the script silently ensures it completes its task uninterrupted.

If you’re diving deeper into batch scripting, you might find these guides handy:

  • Measure how long a batch file takes to execute
  • Fix broken EXE or LNK file associations
  • Enable or disable Windows features using the command line
  • Trigger UAC elevation from the command line

Conclusion

You can easily convert a batch file into an EXE using:

  • Slimm Bat To Exe Converter – Simple and user-friendly.
  • IExpress – No extra software needed.
  • AutoIt – Custom scripting option.
  • Task Scheduler – Best for silent, scheduled execution.

Each method has its advantages, so choose the one that fits your needs. Have questions? Let us know in the comments!

Как мне скрыть командную строку?

Всем привет. Я написал скрипт для командной строки (bat). Хочу чтобы он запускался при включении системы, но при этом окно командной строки не появлялось. Как мне это сделать?


  • Вопрос задан

  • 3132 просмотра

Создайте .vbs файл

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "<путь к .bat файлу>" & Chr(34), 0
Set WshShell = Nothing

и его уже добавляйте в автозагрузку.

Пригласить эксперта

Там пляски с бубном будут, вроде.

task scheduler — создаешь задачу с тригером на старте компьютера
там есть опция — проверять, загружен ли пользователь или нет, если включить то окно не должно показываться (или наоборот выключить) еще есть опция — интерактивно (я уже забыл как там все выглядит)

Ещё одна альтернатива — утилита runhiddenconsole

Ковертируйте .bat в .exe
BatToExeConverter
Можете добавить exe в автозагрузку либо создать задачу в планировщике задач.
Всего наилучшего!

Войдите, чтобы написать ответ


  • Показать ещё
    Загружается…

Минуточку внимания

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Vietcong не запускается на windows 10
  • Gprinter gp 2120t драйвер windows 10
  • Синтез речи в windows 7
  • Как увеличить файл подкачки windows server 2012
  • Как уменьшить частоту процессора windows 10