Командная строка windows запуск в фоновом режиме

In linux you can use command & to run command on the background, the same will continue after the shell is offline. I was wondering is there something like that for windows…

In linux you can use command & to run command on the background, the same will continue after the shell is offline. I was wondering is there something like that for windows…

Josh Withee's user avatar

Josh Withee

9,2063 gold badges40 silver badges57 bronze badges

asked Jan 9, 2014 at 21:08

Louis's user avatar

4

I believe the command you are looking for is start /b *command*

For unix, nohup represents ‘no hangup’, which is slightly different than a background job (which would be *command* &. I believe that the above command should be similar to a background job for windows.

answered Jan 9, 2014 at 21:13

Oeste's user avatar

OesteOeste

1,0012 gold badges7 silver badges13 bronze badges

3

I’m assuming what you want to do is run a command without an interface (possibly automatically?). On windows there are a number of options for what you are looking for:

  • Best: write your program as a windows service. These will start when no one logs into the server. They let you select the user account (which can be different than your own) and they will restart if they fail. These run all the time so you can automate tasks at specific times or on a regular schedule from within them. For more information on how to write a windows service you can read a tutorial online such as (http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx).

  • Better: Start the command and hide the window. Assuming the command is a DOS command you can use a VB or C# script for this. See here for more information. An example is:

    Set objShell = WScript.CreateObject("WScript.Shell")
    objShell.Run("C:yourbatch.bat"), 0, True
    

    You are still going to have to start the command manually or write a task to start the command. This is one of the biggest down falls of this strategy.

  • Worst: Start the command using the startup folder. This runs when a user logs into the computer

Hope that helps some!

Community's user avatar

answered Jan 9, 2014 at 21:14

drew_w's user avatar

drew_wdrew_w

10.2k4 gold badges28 silver badges49 bronze badges

2

Use the start command with the /b flag to run a command/application without opening a new window. For example, this runs dotnet run in the background:

start /b dotnet run

You can pass parameters to the command/application too. For example, I’m starting 3 instances of this C# project, with parameter values of x, y, and z:

enter image description here

To stop the program(s) running in the background: CTRL + BREAK

In my experience, this stops all of the background commands/programs you have started in that cmd instance.

According to the Microsoft docs:

CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application.

Community's user avatar

answered Oct 23, 2019 at 20:52

Josh Withee's user avatar

Josh WitheeJosh Withee

9,2063 gold badges40 silver badges57 bronze badges

You should also take a look at the at command in Windows. It will launch a program at a certain time in the background which works in this case.

Another option is to use the nssm service manager software. This will wrap whatever command you are running as a windows service.

UPDATE:

nssm isn’t very good. You should instead look at WinSW project. https://github.com/kohsuke/winsw

answered Sep 11, 2016 at 3:18

Nicholas DiPiazza's user avatar

Nicholas DiPiazzaNicholas DiPiazza

9,60511 gold badges77 silver badges143 bronze badges

If you take 5 minutes to download visual studio and make a Console Application for this, your problem is solved.

using System;
using System.Linq;
using System.Diagnostics;
using System.IO;

namespace BgRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting: " + String.Join(" ", args));
            String arguments = String.Join(" ", args.Skip(1).ToArray());
            String command = args[0];

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(command);
            p.StartInfo.Arguments = arguments;
            p.StartInfo.WorkingDirectory = Path.GetDirectoryName(command);
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.Start();
        }
    }
}

Examples of usage:

BgRunner.exe php/php-cgi -b 9999
BgRunner.exe redis/redis-server --port 3000
BgRunner.exe nginx/nginx

answered Feb 14, 2021 at 3:19

Afterparty's user avatar

3

It’s unimaginable that after a decade that Windows still doesn’t have a decent way to run commands in background.

start /B command is the most given answer, but the command will be closed when the terminal closed.

Now, Windows 10 have a built-in(you have to install it mannually though) ssh server. you can run

ssh username@localhost "my_backgroud_command --params"

and then CTRL C, close the terminal, the command will continue to run in background.

This is the most decent way I have found so far.
Although not decent enough, because you have to install and configure the ssh server first.

answered Jan 28, 2022 at 4:44

Gary Allen's user avatar

Gary AllenGary Allen

3013 silver badges11 bronze badges

1

An option I use frequently when I need to run a simple command, or set of commands, in the background and then log off, is to script the command(s) (BAT, CMD, PowerShell, et al. … all work fine) and then execute the script using Windows native Task Scheduler. Jobs that are executed from the Task Scheduler do not die when you log off. Task Scheduler jobs can be configured to run as «hidden» i.e. the command prompt window will not be displayed. This script + Task Scheduler is a great alternative rather than developing an executable (e.g. yadda.exe) in your favorite development environment (e.g. Visual Studio) when the task at hand is simple and writing a console application to execute a simple command or two would be «overkill» i.e. more work than it’s worth.

Just my two cents.

Cheers!

answered Jul 21, 2022 at 21:06

InTech97's user avatar

On a windows server here, use a title (in double brackets) , otherwise it will not «release» :

start «» «chrome.exe —parameters» && echo truc

answered Nov 7, 2022 at 15:48

Bastien Gallienne's user avatar

OS Windows XP
Есть консольная программа, которая работает несколько часов, выводит информацию на стандартный поток вывода. Нужно запустить её в фоновом режиме из .bat файла (в этом файле до запуска этой программы выполняются ещё другие нужные действия) так, чтобы не осталось на экране открытого окна, даже консольного (cmd.exe), но при этом вывод программы перенаправить в файл.

Просто фоновый режим (без окна), но без перенаправления в файл работает так.
start /b myprog.exe

Просто перенаправление вывода в файл, но без закрытия окна работает так.
cmd /c «myprog.exe > myfile.txt»
или
myprog.exe > myfile.txt
В любом из этих случаев .bat не заканчивает выполнения, а ждёт завершения этой команды (которая работать будет несколько часов) и не закрывает своё окно, которое зачет-то открыл.

Таким образом, для немедленного завершения .bat файла приходится использовать команду start, иначе никак. Однако команда
start /b myprog.exe > myfile.txt
будет делать не то, что нужно, так как поток перенаправится от команды start, а не от myprog.exe, как нужно.

Единственной возможностью остаётся вложить команду cmd в команду start так.
start /b cmd /c «myprog.exe > myfile.txt»
По описаниям в помощи это должно делать то, что нужно, однако почему-то окно всё равно не закрывается.

Вообще непонятно, зачем понадобилось открывать окно по умолчанию и создавать такие сложности, чтобы его специально закрыть. В OS Linux всё наоборот. По умолчанию окна нет, если оно нужно, то отдельной опцией это указывается. В OS Linux требуемое действие делается очень просто так.
myprog > myfile &

Ещё одна сложность в том, что команда cmd принимает в качестве параметра строку, которую нужно выполнить, что удобно, но не умеет её выполнять, не открывая окна. Команда start как раз сделана для того, чтобы не открывать окно, однако она не умеет выполнять команду в виде строки, а принимает первым параметром имя программы, вторым параметром — первый параметр запускаемой программы и так далее, что делает невозможным перенаправить поток вывода запускаемой программы в файл, так как знак > перенаправит поток вывода команды start.

У каждой из этих двух команд есть преимущества и недостатки, но сделать то, что нужно не получается даже комбинируя их.

Ещё хочу заметить, что очень глупо открывать консольное окно при выполнении программы и не закрывать его, так как оно не всегда нужно. В моём случае закрытие окна вручную не приводит к завершению работы запущенной программы, а просто создаёт пользователю лишние трудности по закрыванию окна. Нужно избавить пользователя от ненужной работы.

Я уже долго мучался сам, советовался с друзьями, но никто не может помочь. Обращаюсь теперь к вам в надежде, что фирма Microsoft всё же лучше знает, как использовать возможности её командной строки для достижения нужного результата. Если ВЫ не поможете, больше обращаться мне не к кому. Это ВАШ программный продукт, всё что можно почерпнуть из помощи по этим командам, я прочитал, но там практически нет ничего нужного.

Помогите, пожалуйста, написать одну строку с командой, но правильно, чтобы она делала то, что нужно. Заранее спасибо.

How can I execute a windows command line in the background, without it interacting with the active user?

slhck's user avatar

slhck

219k68 gold badges591 silver badges578 bronze badges

asked Oct 12, 2010 at 6:09

Mohammad AL-Rawabdeh's user avatar

3

Your question is pretty vague, but there is a post on ServerFault which may contain the information you need. The answer there describes how to run a batch file window hidden:

You could run it silently using a Windows Script file instead. The Run
Method allows you running a script in invisible mode. Create a .vbs
file like this one

Dim WinScriptHost
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:Scheduled Jobsmybat.bat" & Chr(34), 0
Set WinScriptHost = Nothing

and schedule it. The second argument in this example sets the window
style. 0 means «hide the window.»

Tobias Kienzler's user avatar

answered Oct 12, 2010 at 6:30

nhinkle's user avatar

2

This is a little late but I just ran across this question while searching for the answer myself and I found this:

START /B program

which, on Windows, is the closest to the Linux command:

program &

From the console HELP system:

C:>HELP START

Starts a separate window to run a specified program or command.

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
      [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
      [/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
      [command/program] [parameters]

    "title"     Title to display in window title bar.
    path        Starting directory.
    B           Start application without creating a new window. The
                application has ^C handling ignored. Unless the application
                enables ^C processing, ^Break is the only way to interrupt
                the application.

One problem I saw with it is that you have more than one program writing to the console window, it gets a little confusing and jumbled.

To make it not interact with the user, you can redirect the output to a file:

START /B program > somefile.txt

answered May 3, 2013 at 14:28

Novicaine's user avatar

NovicaineNovicaine

3,7112 gold badges11 silver badges2 bronze badges

11

I suspect you mean: Run something in the background and get the command line back immediately with the launched program continuing.

START "" program

Which is the Unix equivalent of

program &

slhck's user avatar

slhck

219k68 gold badges591 silver badges578 bronze badges

answered Sep 30, 2011 at 11:44

Paul Douglas's user avatar

8

START /MIN program 

the above one is pretty closer with its Unix counterpart program &

answered Sep 13, 2012 at 6:55

Siva Sankaran's user avatar

You can use this (commented!) PowerShell script:

# Create the .NET objects
$psi = New-Object System.Diagnostics.ProcessStartInfo
$newproc = New-Object System.Diagnostics.Process
# Basic stuff, process name and arguments
$psi.FileName = $args[0]
$psi.Arguments = $args[1]
# Hide any window it might try to create
$psi.CreateNoWindow = $true
$psi.WindowStyle = 'Hidden'
# Set up and start the process
$newproc.StartInfo = $psi
$newproc.Start()
# Return the process object to the caller
$newproc

Save it as a .ps1 file. After enabling script execution (see Enabling Scripts in the PowerShell tag wiki), you can pass it one or two strings: the name of the executable and optionally the arguments line. For example:

.hideproc.ps1 'sc' 'stop SomeService'

I confirm that this works on Windows 10.

Tobias Kienzler's user avatar

answered Sep 1, 2016 at 22:20

Ben N's user avatar

Ben NBen N

39.4k17 gold badges137 silver badges174 bronze badges

2

This is how my PHP internal server goes into background. So technically it should work for all.

start /B "" php -S 0.0.0.0:8000 &

Thanks

answered Jul 9, 2018 at 4:30

Suyash Jain's user avatar

Suyash JainSuyash Jain

2763 silver badges9 bronze badges

A related answer, with 2 examples:

  1. Below opens calc.exe:

call START /B «my calc» «calc.exe»

  1. Sometimes foreground is not desireable, then you run minimized as below:

call start /min «n» «notepad.exe»

call START /MIN «my mongod» «%ProgramFiles%MongoDBServer3.4binmongod.exe»

Hope that helps.

Community's user avatar

answered Aug 9, 2017 at 5:08

Manohar Reddy Poreddy's user avatar

7

If you want the command-line program to run without the user even knowing about it, define it as a Windows Service and it will run on a schedule.

answered Sep 30, 2011 at 14:00

CarlF's user avatar

CarlFCarlF

8,8163 gold badges24 silver badges40 bronze badges

2

I did this in a batch file:
by starting the apps and sending them to the background. Not exact to the spec, but it worked and I could see them start.

rem   Work Start Batch Job from Desktop
rem   Launchs All Work Apps
@echo off
start "Start OneDrive" "C:UsersusernameAppDataLocalMicrosoftOneDriveOneDrive.exe"
start  "Start Google Sync" "C:Program FilesGoogleDriveGoogleDriveSync.exe"
start skype
start "Start Teams" "C:UsersusernameAppDataLocalMicrosoftTeamscurrentTeams.exe"
start Slack
start Zoom
sleep 10
taskkill /IM "explorer.exe"
taskkill /IM "teams.exe"
taskkill /IM "skype.exe"
taskkill /IM "slack.exe"
taskkill /IM "zoom.exe"
taskkill /IM "cmd.exe"
@echo on

killing explorer kills all explorer windows, I run this batch file after start up, so killing explorer is no issue for me.
You can seemingly have multiple explorer processes and kill them individually but I could not get it to work.
killing cmd.exe is to close the CMD window which starts because of the bad apps erroring.

answered Apr 10, 2021 at 10:22

TheArchitecta's user avatar

2

You can use my utility. I think the source code should be self explanatory. Basically CreateProcess with CREATE_NO_WINDOW flag.

answered Aug 17, 2022 at 15:19

ScienceDiscoverer's user avatar

just came across this thread
windows 7 , using power shell, runs executable’s in the background , exact same as unix filename &

example: start -NoNewWindow filename

help start

NAME
Start-Process

SYNTAX
Start-Process [-FilePath] [[-ArgumentList] ] [-Credential ] [-WorkingDirectory
] [-LoadUserProfile] [-NoNewWindow] [-PassThru] [-RedirectStandardError ] [-RedirectStandardInput
] [-RedirectStandardOutput ] [-Wait] [-WindowStyle {Normal | Hidden |
Minimized | Maximized}] [-UseNewEnvironment] []

Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-WorkingDirectory <string>] [-PassThru] [-Verb
<string>] [-Wait] [-WindowStyle <ProcessWindowStyle> {Normal | Hidden | Minimized | Maximized}]
[<CommonParameters>]

ALIASES
saps
start

answered Jul 13, 2015 at 23:29

jerry's user avatar

1

How can I execute a windows command line in the background, without it interacting with the active user?

slhck's user avatar

slhck

219k68 gold badges591 silver badges578 bronze badges

asked Oct 12, 2010 at 6:09

Mohammad AL-Rawabdeh's user avatar

3

Your question is pretty vague, but there is a post on ServerFault which may contain the information you need. The answer there describes how to run a batch file window hidden:

You could run it silently using a Windows Script file instead. The Run
Method allows you running a script in invisible mode. Create a .vbs
file like this one

Dim WinScriptHost
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:Scheduled Jobsmybat.bat" & Chr(34), 0
Set WinScriptHost = Nothing

and schedule it. The second argument in this example sets the window
style. 0 means «hide the window.»

Tobias Kienzler's user avatar

answered Oct 12, 2010 at 6:30

nhinkle's user avatar

2

This is a little late but I just ran across this question while searching for the answer myself and I found this:

START /B program

which, on Windows, is the closest to the Linux command:

program &

From the console HELP system:

C:>HELP START

Starts a separate window to run a specified program or command.

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
      [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
      [/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
      [command/program] [parameters]

    "title"     Title to display in window title bar.
    path        Starting directory.
    B           Start application without creating a new window. The
                application has ^C handling ignored. Unless the application
                enables ^C processing, ^Break is the only way to interrupt
                the application.

One problem I saw with it is that you have more than one program writing to the console window, it gets a little confusing and jumbled.

To make it not interact with the user, you can redirect the output to a file:

START /B program > somefile.txt

answered May 3, 2013 at 14:28

Novicaine's user avatar

NovicaineNovicaine

3,7112 gold badges11 silver badges2 bronze badges

11

I suspect you mean: Run something in the background and get the command line back immediately with the launched program continuing.

START "" program

Which is the Unix equivalent of

program &

slhck's user avatar

slhck

219k68 gold badges591 silver badges578 bronze badges

answered Sep 30, 2011 at 11:44

Paul Douglas's user avatar

8

START /MIN program 

the above one is pretty closer with its Unix counterpart program &

answered Sep 13, 2012 at 6:55

Siva Sankaran's user avatar

You can use this (commented!) PowerShell script:

# Create the .NET objects
$psi = New-Object System.Diagnostics.ProcessStartInfo
$newproc = New-Object System.Diagnostics.Process
# Basic stuff, process name and arguments
$psi.FileName = $args[0]
$psi.Arguments = $args[1]
# Hide any window it might try to create
$psi.CreateNoWindow = $true
$psi.WindowStyle = 'Hidden'
# Set up and start the process
$newproc.StartInfo = $psi
$newproc.Start()
# Return the process object to the caller
$newproc

Save it as a .ps1 file. After enabling script execution (see Enabling Scripts in the PowerShell tag wiki), you can pass it one or two strings: the name of the executable and optionally the arguments line. For example:

.hideproc.ps1 'sc' 'stop SomeService'

I confirm that this works on Windows 10.

Tobias Kienzler's user avatar

answered Sep 1, 2016 at 22:20

Ben N's user avatar

Ben NBen N

39.4k17 gold badges137 silver badges174 bronze badges

2

This is how my PHP internal server goes into background. So technically it should work for all.

start /B "" php -S 0.0.0.0:8000 &

Thanks

answered Jul 9, 2018 at 4:30

Suyash Jain's user avatar

Suyash JainSuyash Jain

2763 silver badges9 bronze badges

A related answer, with 2 examples:

  1. Below opens calc.exe:

call START /B «my calc» «calc.exe»

  1. Sometimes foreground is not desireable, then you run minimized as below:

call start /min «n» «notepad.exe»

call START /MIN «my mongod» «%ProgramFiles%MongoDBServer3.4binmongod.exe»

Hope that helps.

Community's user avatar

answered Aug 9, 2017 at 5:08

Manohar Reddy Poreddy's user avatar

7

If you want the command-line program to run without the user even knowing about it, define it as a Windows Service and it will run on a schedule.

answered Sep 30, 2011 at 14:00

CarlF's user avatar

CarlFCarlF

8,8163 gold badges24 silver badges40 bronze badges

2

I did this in a batch file:
by starting the apps and sending them to the background. Not exact to the spec, but it worked and I could see them start.

rem   Work Start Batch Job from Desktop
rem   Launchs All Work Apps
@echo off
start "Start OneDrive" "C:UsersusernameAppDataLocalMicrosoftOneDriveOneDrive.exe"
start  "Start Google Sync" "C:Program FilesGoogleDriveGoogleDriveSync.exe"
start skype
start "Start Teams" "C:UsersusernameAppDataLocalMicrosoftTeamscurrentTeams.exe"
start Slack
start Zoom
sleep 10
taskkill /IM "explorer.exe"
taskkill /IM "teams.exe"
taskkill /IM "skype.exe"
taskkill /IM "slack.exe"
taskkill /IM "zoom.exe"
taskkill /IM "cmd.exe"
@echo on

killing explorer kills all explorer windows, I run this batch file after start up, so killing explorer is no issue for me.
You can seemingly have multiple explorer processes and kill them individually but I could not get it to work.
killing cmd.exe is to close the CMD window which starts because of the bad apps erroring.

answered Apr 10, 2021 at 10:22

TheArchitecta's user avatar

2

You can use my utility. I think the source code should be self explanatory. Basically CreateProcess with CREATE_NO_WINDOW flag.

answered Aug 17, 2022 at 15:19

ScienceDiscoverer's user avatar

just came across this thread
windows 7 , using power shell, runs executable’s in the background , exact same as unix filename &

example: start -NoNewWindow filename

help start

NAME
Start-Process

SYNTAX
Start-Process [-FilePath] [[-ArgumentList] ] [-Credential ] [-WorkingDirectory
] [-LoadUserProfile] [-NoNewWindow] [-PassThru] [-RedirectStandardError ] [-RedirectStandardInput
] [-RedirectStandardOutput ] [-Wait] [-WindowStyle {Normal | Hidden |
Minimized | Maximized}] [-UseNewEnvironment] []

Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-WorkingDirectory <string>] [-PassThru] [-Verb
<string>] [-Wait] [-WindowStyle <ProcessWindowStyle> {Normal | Hidden | Minimized | Maximized}]
[<CommonParameters>]

ALIASES
saps
start

answered Jul 13, 2015 at 23:29

jerry's user avatar

1

Download PC Repair Tool to quickly find & fix Windows errors automatically

Even though batch files are like vintage when it comes to operating systems, they are one of the best ways to get things done. If you are in a kind of work that asks you to run some pre-defined commands every day, the console windows are annoying, especially when you are sure they are perfect and will not make any mistake. This guide will learn how you can run Batch Files silently in background mode and hide the Console Window.

If you have a simple batch (.BAT) file that you want to run, you can create another batch file and type in the command mentioned below:

START /MIN CMD.EXE /C mysecondbatchfile.bat

There are two ways to execute it.

  • Run it from within the command prompt.
  • Create a shortcut on your desktop, and point it towards the bat file. Make sure to change the Properties of the shortcut as Start minimized.

Run batch files silently using a Scheduled Task

Windows has tons of features that are not used. The Task Scheduler is one of them. This feature allows you to run tasks in the background, periodically or every day. You can easily schedule a Batch file to run automatically using Scheduled Task with options available out of the box.

Here is the procedure to use it.

  • Type “Task Scheduler” in the Cortana box, and you should see the app listed. You can also choose to type “taskschd.msc” into the Run prompt (Win + R) to open it.
  • On the last pane on the right-hand side, look for an option that says Create Basic Task. Click on it to open.
  • It launches a wizard which will ask you
    • Name of Task with a description
    • When do you want to start the task? You can choose between Daily, Weekly, Monthly, OneTime, When the computer starts and so on.
    • Next, select a program, and it will offer to choose a program or script, add arguments, start in details, and so on.
  • Using this, you can add everything a bat file would need. In the end, select open properties window for further configuration.Run Batch Files silently
  • In the properties window, you can choose to run the program even when is the user is logged out to make sure your program is working round the clock. Make sure to choose Hidden.
  • Add admin privilege permission by selecting the “Run with highest privileges” box. Click OK when done,
  • To test, the task works exactly as you need it to, right-click and selecting Run.

Task Scheduler Properties for Batch File

Run Batch Files silently & hide the console window using freeware

1] Hidden Start or HStart

Hstart UI to run batch files silently

It’s a lightweight command-line utility that allows you to run console applications and batch files without any window, in the background. It can even handle UAC privilege elevation and also run multiple commands in parallel or in sync. The program offers a user interface that makes it easy to set things.

  • Drag, and drop the batch file onto the interface.
  • Choose options including hiding console windows, UAC, and so on.
  • You can also test it using test mode.
  • You can also add command-line options if needed.
  • Directly created shortcut and autostart entry from the interface

You can download it from here from ntwind.com

2] SilentCMD

If you are comfortable with the command line, i.e., typing and using a command prompt, SilentCMD offers tons of features and does our job as well. You can type in SilentCMD [path to .bat file] [arguments], and it gets the job done, quietly. Additionally, you can log in the output and errors into a text file.

SilentCMD [BatchFile [BatchArguments]] [Options]

Options:
    /LOG:file :: output status to LOG file (overwrite existing log)
   /LOG+:file :: output status to LOG file (append to existing log)
   /DELAY:seconds :: delay the execution of batch file by x seconds

You can download it from Github.

How to Make an executable file from a Batch Script?

Executables are probably the best way to run batch files along with an option to hide your script from everyone else. There are many options available to make an executable file from a Batch Script and making an EXE is very simple.  However, if your antivirus catches it, make sure to mark it safe as you are only using it for personal use.

Check out our detailed posts on the following subjects:

  • How to convert BAT to EXE file
  • You can script batch programs and compile them into an EXE file with Batch Compiler.
  • Convert VBS to EXE using an Online tool or VBScript converter software.

Incidentally, Slimm Bat To Exe Converter offers three types of modes including express, windowless, and custom.  You can download it from Softpedia.

These should be enough for you to create and run Batch Files silently on your Windows 11/10 PC. However, always test it before making them run quietly. You never want to lose your data because you didn’t test something properly.

What is @echo in a batch file?

Echo is the command that can display or suppress the output of commands that are executed from the BAT file. When you plan to run a natch file silently, use @echo off at the start of the file. You can also use it o display a message using echo <message>

Do BAT files need admin permission to execute?

BAT files only process or run commands; they do not need admin permission. However, if any of the commands that it tries to run requires admin permission, it will prompt you with UAC. That said, if you run the BAT file with admin permission, all the subsequent commands should execute with the same permission.

Ezoic

Ashish is a veteran Windows and Xbox user who excels in writing tips, tricks, and features on it to improve your day-to-day experience with your devices. He has been a Microsoft MVP (2008-2010).

Download PC Repair Tool to quickly find & fix Windows errors automatically

Even though batch files are like vintage when it comes to operating systems, they are one of the best ways to get things done. If you are in a kind of work that asks you to run some pre-defined commands every day, the console windows are annoying, especially when you are sure they are perfect and will not make any mistake. This guide will learn how you can run Batch Files silently in background mode and hide the Console Window.

If you have a simple batch (.BAT) file that you want to run, you can create another batch file and type in the command mentioned below:

START /MIN CMD.EXE /C mysecondbatchfile.bat

There are two ways to execute it.

  • Run it from within the command prompt.
  • Create a shortcut on your desktop, and point it towards the bat file. Make sure to change the Properties of the shortcut as Start minimized.

Run batch files silently using a Scheduled Task

Windows has tons of features that are not used. The Task Scheduler is one of them. This feature allows you to run tasks in the background, periodically or every day. You can easily schedule a Batch file to run automatically using Scheduled Task with options available out of the box.

Here is the procedure to use it.

  • Type “Task Scheduler” in the Cortana box, and you should see the app listed. You can also choose to type “taskschd.msc” into the Run prompt (Win + R) to open it.
  • On the last pane on the right-hand side, look for an option that says Create Basic Task. Click on it to open.
  • It launches a wizard which will ask you
    • Name of Task with a description
    • When do you want to start the task? You can choose between Daily, Weekly, Monthly, OneTime, When the computer starts and so on.
    • Next, select a program, and it will offer to choose a program or script, add arguments, start in details, and so on.
  • Using this, you can add everything a bat file would need. In the end, select open properties window for further configuration.Run Batch Files silently
  • In the properties window, you can choose to run the program even when is the user is logged out to make sure your program is working round the clock. Make sure to choose Hidden.
  • Add admin privilege permission by selecting the “Run with highest privileges” box. Click OK when done,
  • To test, the task works exactly as you need it to, right-click and selecting Run.

Task Scheduler Properties for Batch File

Run Batch Files silently & hide the console window using freeware

1] Hidden Start or HStart

Hstart UI to run batch files silently

It’s a lightweight command-line utility that allows you to run console applications and batch files without any window, in the background. It can even handle UAC privilege elevation and also run multiple commands in parallel or in sync. The program offers a user interface that makes it easy to set things.

  • Drag, and drop the batch file onto the interface.
  • Choose options including hiding console windows, UAC, and so on.
  • You can also test it using test mode.
  • You can also add command-line options if needed.
  • Directly created shortcut and autostart entry from the interface

You can download it from here from ntwind.com

2] SilentCMD

If you are comfortable with the command line, i.e., typing and using a command prompt, SilentCMD offers tons of features and does our job as well. You can type in SilentCMD [path to .bat file] [arguments], and it gets the job done, quietly. Additionally, you can log in the output and errors into a text file.

SilentCMD [BatchFile [BatchArguments]] [Options]

Options:
    /LOG:file :: output status to LOG file (overwrite existing log)
   /LOG+:file :: output status to LOG file (append to existing log)
   /DELAY:seconds :: delay the execution of batch file by x seconds

You can download it from Github.

How to Make an executable file from a Batch Script?

Executables are probably the best way to run batch files along with an option to hide your script from everyone else. There are many options available to make an executable file from a Batch Script and making an EXE is very simple.  However, if your antivirus catches it, make sure to mark it safe as you are only using it for personal use.

Check out our detailed posts on the following subjects:

  • How to convert BAT to EXE file
  • You can script batch programs and compile them into an EXE file with Batch Compiler.
  • Convert VBS to EXE using an Online tool or VBScript converter software.

Incidentally, Slimm Bat To Exe Converter offers three types of modes including express, windowless, and custom.  You can download it from Softpedia.

These should be enough for you to create and run Batch Files silently on your Windows 11/10 PC. However, always test it before making them run quietly. You never want to lose your data because you didn’t test something properly.

What is @echo in a batch file?

Echo is the command that can display or suppress the output of commands that are executed from the BAT file. When you plan to run a natch file silently, use @echo off at the start of the file. You can also use it o display a message using echo <message>

Do BAT files need admin permission to execute?

BAT files only process or run commands; they do not need admin permission. However, if any of the commands that it tries to run requires admin permission, it will prompt you with UAC. That said, if you run the BAT file with admin permission, all the subsequent commands should execute with the same permission.

Ezoic

Ashish is a veteran Windows and Xbox user who excels in writing tips, tricks, and features on it to improve your day-to-day experience with your devices. He has been a Microsoft MVP (2008-2010).

Как я могу выполнить командную строку Windows в фоновом режиме, не взаимодействуя с активным пользователем?

задан Mohammad AL-Rawabdeh836

Это немного поздно, но я просто наткнулся на этот вопрос, когда искал ответ сам, и нашел это:

START /B program

которая в Windows наиболее близка к команде Linux:

program &

Из консольной системы HELP:

C:>HELP START

Starts a separate window to run a specified program or command.

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
      [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
      [/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
      [command/program] [parameters]

    "title"     Title to display in window title bar.
    path        Starting directory.
    B           Start application without creating a new window. The
                application has ^C handling ignored. Unless the application
                enables ^C processing, ^Break is the only way to interrupt
                the application.

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

Чтобы он не взаимодействовал с пользователем, вы можете перенаправить вывод в файл:

START /B program > somefile.txt

Я подозреваю, что вы имеете в виду: запустить что-то в фоновом режиме и немедленно вернуть командную строку с продолжением запущенной программы.

START "" program

Какой Unix-эквивалент

program &

ответ дан Paul Douglas641

Ваш вопрос довольно расплывчатый, но на ServerFault есть сообщение, которое может содержать необходимую информацию. Ответ там описывает, как запустить скрытое окно командного файла:

Вы можете запустить его без вывода сообщений, используя файл сценария Windows. Метод Run позволяет запускать скрипт в невидимом режиме. Создайте файл .vbs как этот

Dim WinScriptHost
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:Scheduled Jobsmybat.bat" & Chr(34), 0
Set WinScriptHost = Nothing

и наметить это. Второй аргумент в этом примере устанавливает стиль окна. 0 означает «скрыть окно».

изменён Tobias Kienzler2k

START /MIN program 

вышеупомянутый довольно близок с его партнерской программой Unix program &

ответ дан Siva Sankaran221

Вы можете использовать это (прокомментировал!) Скрипт PowerShell:

# Create the .NET objects
$psi = New-Object System.Diagnostics.ProcessStartInfo
$newproc = New-Object System.Diagnostics.Process
# Basic stuff, process name and arguments
$psi.FileName = $args[0]
$psi.Arguments = $args[1]
# Hide any window it might try to create
$psi.CreateNoWindow = $true
$psi.WindowStyle = 'Hidden'
# Set up and start the process
$newproc.StartInfo = $psi
$newproc.Start()
# Return the process object to the caller
$newproc

Сохраните его как файл .ps1 . После включения выполнения сценария (см. «Включение сценариев» в вики-теге PowerShell) вы можете передать ему одну или две строки: имя исполняемого файла и, необязательно, строку аргументов. Например:

.hideproc.ps1 'sc' 'stop SomeService'

Я подтверждаю, что это работает на Windows 10.

изменён Tobias Kienzler2k

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

Вот как мой внутренний сервер PHP переходит в фоновый режим. Технически это должно работать для всех.

start /B "" php -S 0.0.0.0:8000 &

Спасибо

Соответствующий ответ с двумя примерами:

  1. Ниже открывается calc.exe:

вызовите START /B «мой calc» «calc.exe»

  1. Иногда передний план нежелателен, тогда вы запускаете свернутый, как показано ниже:

вызовите START /MIN «my mongod» «% ProgramFiles%MongoDBServer3.4binmongod.exe»

ответ дан Manohar Reddy Poreddy161

Пример :

start /MIN /B grep -noid включает * .c 1> log.txt 2> 1 &

Запускает grep в backgound, перенаправляя как stdout && stderr в log.txt

только что наткнулся на этот поток Windows 7, используя Power Shell, запускает исполняемые файлы в фоновом режиме, точно так же, как имя файла Unix &

пример: start -NoNewWindow filename

помочь начать

NAME Start-Process

SYNTAX Start-Process [-FilePath] [[-ArgumentList]] [-Credential] [-WorkingDirectory] [-LoadUserProfile] [-NoNewWindow] [-PassThru] [-RedirectStandardError] [-RedirectStandardInput] [-Red [-WindowStyle {Normal | Скрытый | Минимизировано | Развернуто}] [-UseNewEnvironment] []

Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-WorkingDirectory <string>] [-PassThru] [-Verb
<string>] [-Wait] [-WindowStyle <ProcessWindowStyle> {Normal | Hidden | Minimized | Maximized}]
[<CommonParameters>]

Псевдоним соки начало

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

Содержание

  1. Запускать пакетные файлы в Windows без вывода сообщений
  2. Запускать пакетные файлы без вывода сообщений, используя запланированное задание
  3. Запускать пакетные файлы без вывода сообщений и скрывать окно консоли с помощью бесплатного программного обеспечения.
  4. Создайте исполняемый файл из пакетного скрипта

Запускать пакетные файлы в Windows без вывода сообщений

Если у вас есть простой пакетный файл, который вы хотите запустить, вы можете создать другой пакетный файл и ввести команду, как показано ниже

 START/MIN CMD.EXE/C mysecondbatchfile.bat 

Есть два способа выполнить это.

  • Запустите его из командной строки.
  • Создайте ярлык на рабочем столе и наведите его на файл bat. Обязательно измените свойства ярлыка на Начать сворачиваться .

Запускать пакетные файлы без вывода сообщений, используя запланированное задание

Windows имеет множество функций, которые не используются. Планировщик заданий является одним из них. Эта функция позволяет запускать задачи в фоновом режиме, периодически или каждый день. Вы можете легко запланировать запуск командного файла автоматически, используя запланированную задачу с опциями, доступными из коробки.

Вот процедура, чтобы использовать это.

  • Введите «Task Scheduler» в поле Cortana, и вы должны увидеть приложение в списке. Вы также можете ввести «taskschd.msc» в командной строке, чтобы открыть его.
  • На последней панели справа найдите параметр, который гласит Создать базовое задание. Нажмите на него, чтобы открыть.
  • Это запускает мастера, который спросит вас

    • Наименование задачи с описанием
    • Когда вы хотите начать задание? Вы можете выбрать между Ежедневно, Еженедельно, Ежемесячно, OneTime, Когда компьютер запускается и так далее.
    • Далее выберите программу, и она предложит выбрать программу или сценарий, добавить аргументы, подробно начать и так далее.
  • Используя это, вы можете добавить все, что понадобится файлу bat. В конце выберите открытое окно свойств для дальнейшей настройки.
  • В окне свойств вы можете выбрать запуск программы, даже если пользователь вышел из системы, чтобы убедиться, что ваша программа работает круглосуточно. Обязательно выберите Скрытый.
  • Добавьте разрешение привилегий администратора, установив флажок « Запуск с самыми высокими привилегиями ». Нажмите OK, когда закончите,
  • Чтобы проверить, задача работает именно так, как вам нужно, щелкните правой кнопкой мыши и выберите «Выполнить».

Запускать пакетные файлы без вывода сообщений и скрывать окно консоли с помощью бесплатного программного обеспечения.

1] Скрытый старт или HStart

Это легкая утилита командной строки, которая позволяет запускать консольные приложения и командные файлы без каких-либо окон в фоновом режиме. Он может даже обрабатывать повышение привилегий UAC, а также выполнять несколько команд параллельно или синхронно. Программа предлагает пользовательский интерфейс, который позволяет легко устанавливать вещи.

  • Перетащите пакетный файл в интерфейс.
  • Выберите параметры, в том числе скрытие окон консоли, UAC и т. Д.
  • Вы также можете проверить это, используя тестовый режим.
  • Вы также можете добавить параметры командной строки, если это необходимо.
  • Непосредственно созданный ярлык и автозапуск записи из интерфейса

Вы можете скачать здесь.

2] SilentCMD

Если вы знакомы с командной строкой, то есть набираете и используете командную строку, SilentCMD предлагает множество функций и выполняет нашу работу. Вы можете ввести SilentCMD [путь к файлу .bat] [аргументы], и он спокойно выполнит свою работу. Кроме того, вы можете войти в вывод и ошибки в текстовом файле.

  SilentCMD [BatchFile [BatchArguments]] [Параметры]
Опции:/LOG: файл :: состояние вывода в файл LOG (перезаписать существующий журнал)/LOG +: файл :: статус вывода в файл LOG (добавить в существующий журнал)/DELAY: секунд :: задержать выполнение пакетного файла на х секунд  

Вы можете скачать его с Github.

Создайте исполняемый файл из пакетного скрипта

Исполняемые файлы, вероятно, являются лучшим способом запуска командных файлов вместе с возможностью скрыть ваш скрипт от всех остальных. Существует много вариантов создания исполняемого файла из пакетного скрипта, а создание EXE-файла очень просто. Однако, если ваш антивирус его ловит, обязательно отметьте его как безопасный, поскольку вы используете его только для личного использования.

Проверьте наши подробные сообщения на следующие темы:

  • Как преобразовать BAT в EXE-файл
  • Вы можете создавать сценарии пакетных программ и компилировать их в файл .exe с помощью Batch Compiler.
  • Конвертировать VBS в EXE с помощью онлайн-инструмента или программного обеспечения для конвертации VBScript.

Кстати, Slimm Bat To Exe Converter предлагает три типа режимов: экспресс, без окон и пользовательский. Вы можете скачать его с Softpedia.

Их должно быть достаточно для создания и запуска пакетных файлов в режиме без вывода сообщений на ПК с Windows 10. Тем не менее, всегда проверяйте это, прежде чем заставить их работать спокойно. Вы никогда не хотите потерять свои данные, потому что вы не проверяли что-то должным образом.

Групповое
выполнение:

В
командной строке Windows NT/2000/XP можно
использовать специальные символы,
которые позволяют вводить несколько
команд одновременно и управлять работой
команд в зависимости от результатов их
выполнения. С помощью таких символов
условной обработки можно содержание
небольшого пакетного файла записать в
одной строке и выполнить полученную
составную команду.

Используя
символ амперсанда &,
можно разделить несколько утилит в
одной командной строке, при этом они
будут выполняться друг за другом.
Например, если набрать команду DIR
& PAUSE & COPY /? и
нажать клавишу <Enter>, то вначале на
экран будет выведено содержимое текущего
каталога, а после нажатия любой клавиши
— встроенная справка команды COPY.

Символ ^ позволяет
использовать командные символы как
текст, то есть при этом происходит
игнорирование значения специальных
символов. Например, если ввести в
командной строке

ECHO
Абв & COPY /?

и
нажать клавишу <Enter>, то произойдет
выполнение подряд двух команд: ECHO
Абв и COPY
/? (команда
ECHOвыводит
на экран символы, указанные в командной
строке после нее).

Выполнение
программ в фоновом режиме

Большинство
оболочек представляют возможность
запуска и последующего выполнения
программ как фоновых процессов. Запуск
команды в качестве фоновой означает,
что команда выполняется в оперативной
памяти, в то время как управление
командной строкой оболочки возвращается
вашей консоли. Это удобный способ работы
в Linux, в особенности, если вы работаете
на отдельном терминале, вам не достает
места на экране при работе в Х11 или ваша
система обладает избытком оперативной
памяти. Такие задачи, как сортировка
больших файлов или поиск в каталогах и
других файловых системах, неплохие
кандидаты на выполнение в фоновом
Режиме.

Несмотря
на то, что Linux представляет возможность
работы с виртуальными консолями, а
многочисленные диспетчеры окон Х11 дают
возможность работать с разными рабочими
столами, в процессе работы с Linux вы,
скорее всего, неоднократно будете
выполнять программы в фоновом режиме.

Для
запуска программ в фоновом режиме в
конец командной строки добавляется
символ амперсанда (&). Например, для
запуска еще одной программы с терминала
Х11 вам может потребоваться запустить
эту программу в фоновом режиме, чтобы
ваш текущий терминал оставался свободным
для вывода: # rxvt &

Эта
команда запускает терминал rxvt, и
приглашение вашей командной строки
вновь становится свободным для ввода.

59. Использование переменных в командных оболочках ос.

Среда
командной оболочки Cmd.exe определяется
переменными, задающими поведение
командной оболочки и операционной
системы. Имеется возможность определить
поведение среды командной оболочки или
среды всей операционной системы с
помощью двух типов переменных среды:
системных и локальных. Системные
переменные среды определяют поведение
глобальной среды операционной системы.
Локальные переменные среды определяют
поведение среды в данном экземпляре
Cmd.exe. Системные переменные среды заданы
заранее в операционной системе и доступны
для всех процессов Windows XP. Только
пользователи с привилегиями администратора
могут изменять эти переменные. Эти
переменные наиболее часто используются
в сценариях входа в систему. Локальные
переменные среды доступны, только когда
пользователь, для которого они были
созданы, вошел в систему. Локальные
переменные из куста HKEY_CURRENT_USER подходят
только для текущего пользователя, но
определяют поведение глобальной среды
операционной системы. В следующем списке
представлены различные типы переменных
в порядке убывания приоритета.


Встроенные системные переменные


Системные переменные куста HKEY_LOCAL_MACHINE


Локальные переменные куста HKEY_CURRENT_USER

— Все
переменные среды и пути указаны в файле
Autoexec.bat.

— Все
переменные среды и пути указаны в
сценарии входа в систему (если он
имеется).


Переменные, используемые интерактивно
в сценарии или пакетном файле

Соседние файлы в папке Экзамен

  • #
  • #
  • #

Понравилась статья? Поделить с друзьями:
  • Командная строка windows для чайников обучающий видеокурс торрент
  • Команда таймер сна на компьютер windows 10
  • Командная строка windows xp не видит флешку
  • Команда спящий режим в windows 10 ярлык
  • Командная строка windows 8 через биос