How to run a command in the background on Windows? - 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…

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.

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!

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:
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.

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

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

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.

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!

On a windows server here, use a title (in double brackets) , otherwise it will not "release" :
start "" "chrome.exe --parameters" && echo truc

Related

Can UiPath process be converted into binary executable?

I have a process in UiPath to automate PyCharm, a really simple one like just running a Python script and copying the run message into a text file. Now I want to convert it into a binary file to be executed on a windows machine.
I came to know that UiPath did have an option for exporting projects into executable files but sadly it was also removed.
I also reviewed the orchestrator for UiPath but that does seem meaningful to me. I didn't understand why a company would remove such a crucial feature (conversion to executable) and provide a messy solution like this. May be I'm missing something.
My question is....
Is there any workaround, any third party trick that can convert an UiPath project into windows executable file.
UiPath does not want users to be able to run executables directly. They are forcing users to use Orchestrator. So they always have the full control about the users and their licensing model. If they would still offer the executable way, someone could easily create a Task with UiPath and send this to any other PC without using a UiPath account. So this is mainly the reason they stopped offering this method. But you still have some other options to run your process so don't worry.
Those ways are:
Use Orchestrator. Run process from your Orchestrator dashboard (via Jobs manually or time triggered or even another starting trigger).
Use Orchestrator and use UiPath Robot (comes already with the UiPath installation). Now you can simply start it from tray icon.
Use UiPath Studio and start process from here.
Create a batch file that runs the start command script for your process. This line UiRobot.exe_Path /file:"Main.xaml" will run your process.
Create a Visual Studio application (exe) that runs the batch file from #4.
Use REST API to run the process.
As you can see you have several options but unfortunately the exe workaround is just a wrapper for the batch file.
I would recommend you to use Orchestrator, as it gives you so many possibilities and control on your processes and a good logging.
The simplest way to do this would be to call the UiPath Robot Command Line Interface within a batch file. I suggest that you package the process first and then refer to that package in the batch file using the UiPath.exe execute command with the --process {Package_ID} argument. You can add UiPath.exe to your PATH environment variable so you don't need to use an absolute path to the exe in your batch file. The batch file will be able to run on your Windows VM just like an executable. Alternatively, you could add a shortcut to UiPath.exe and add the arguments to the target of the shortcut in the properties menu of the shortcut.
I'm using AutoHotkey script for this purpose and thought I'd share my method,
Create a *.ahk script using below code,
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn ; Enable warnings to assist with detecting common errors.
#SingleInstance force
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
SetTitleMatchMode,2
DetectHiddenWindows, On
; you don't need to modify below code unless UiPath Studio changes its shortcut name
EnvGet, LocalFolder, LocalAppData ;use windows Env variable to get local appdata folder
UiPath=%LocalFolder%\UiPath
UiPath_ShrtCut=%A_Programs%\UiPath Studio.lnk
UiPath_Prcss:="UiPath.Studio.exe"
UiPath_Asstnt:="UiPath.Assistant.exe"
FileGetShortcut, %UiPath_ShrtCut%, , OutDir ;get parent directory of shortcut.lnk
;modify your_script_path\Main as per your script and its path
Script=""%OutDir%\UiRobot.exe" "-file" "your_script_path\Main.xaml"" ;script folder and script name
; you can add additional clause in here
If (FileExist(UiPath) "D")
{
Process, Exist, %UiPath_Asstnt%
if ErrorLevel = 0
{
Runwait, %UiPath_ShrtCut%
WinWait, ahk_exe %UiPath_Asstnt% ;wait for UiPath.Assistant to load
Sleep, 2500
Runwait, %comspec% /c TASKKILL /im %UiPath_Prcss% /f ,,Hide ;now kill UiPath main window
;Run, %A_AHKPath% %Rec_Script% ;run record
Run, %comspec% /c %Script%,,Hide
}
else
{
;Run, %A_AHKPath% %Rec_Script% ;run record
Run, %comspec% /c %Script%,,Hide
}
}
return
Then create a task schedule as per your desired trigger and use following in action tab,
Program/Script: "C:\Program Files\AutoHotkey\AutoHotkey.exe"
Add Arguments (optional): "Script_path\Script_name.ahk"

How do I tell a windows batch script to execute the next line without waiting for the previous line to finish executing?

I'm setting up a .cmd script to be run on startup for a pseudo-server (It's actually a laptop, but that's irrelevant) to automatically launch pageant, load an SSH key, connect to an SSH server using Putty (Pageant would automatically authenticate with the key), then launch mIRC which in turn has a series of scripts setup to operate as an IRC bot and automatically connect to networks using putty as an SSH tunnel.
With that in mind, I have the below code in a startup.cmd file:
"C:\Program Files (x86)\PuTTY\pageant.exe" c:\Path\To\Private\Key.ppk
"C:\Program Files (x86)\PuTTY\putty.exe" -ssh user#host
"C:\Program Files (x86)\mIRC\mirc.exe"
EXIT
When I test run this file, the command prompt runs the first line, launches pageant, and then sits there and does nothing until I close pageant completely. I believe I have an idea on what the issue here is, but I can't find any information on how to resolve this in a batch file.
I do know on linux systems, if I were running a bash script to do something similar, I would want to have a & symbol at the end of each line to tell it to run the next command without waiting for the previous command to finish executing. I did try that in the batch script in the off chance that would work (It didn't).
For those who may ask, this is on Windows 8.1 64 bit. The user running this script is not an administrator.
I can't comment to expand on Squashman's suggestion, so let me answer here.
In your case, if you only want to have Pageant running in the background, without interacting with it, I think it's best to run:
START "" /B <your command>
The /B parameter will spawn the process without launching a new window for it, which seems like something you'd like to avoid (anyway, it's probably closest to the behaviour you can obtain in Linux with &).
Please note that if you close the window from which you spawned this process, it will terminate as well.

Open Excel on Jenkins CI

I am working on Windows 7 (logged in as session no.1), my Jenkins CI is running as windows service in session 0.
My problem is.. I want to open an Excel file through Jenkins CI in session 0, but want to display its GUI on session 1.
I know that session 0 is isolated in Windows 7, but is it possible to run a process in session 0 and then output in another session? please help.
Edit:
Took a little trial and error, but this is what finally worked for me (Windows 7 64-bit).
Download PsTools from Microsoft site
We only need psexec.exe, but you can extract everything. Extract to some location accessible by Jenkins, preferably without spaces in the path.
Open elevated command prompt: type cmd into Start's quicksearch, right click cmd.exe, select Run as Administrator.
Type C:\path\to\psexec.exe -accepteula and press enter.
Type C:\path\to\psexec.exe -i 1 cmd and press enter. (If you see a command prompt appear, all is good, close it now)
In Job configuration, configure Execute Windows Batch command step
Write the following:
C:\path\to\psexec.exe -accepteula && C:\path\to\psexec.exe -i 1 cmd /c start C:\PROGRA~2\MICROSO~1\path\to\excel.exe
Where:
C:\path\to is your full path to psexec.exe, unless it is in your %path%
-i 1 is the session ID that you want to launch in.
C:\PROGRA~2\MICROSO~1\path\to is your full path to excel.exe without spaces. Since most Office installations are going to be under paths with spaces, like "Program Files (x86), you have to figure out the short path, or place it somewhere without spaces.
Having excel.exe under %path% and working from regular command line was not enough.
A little explanation for those that care:
psexec needs to install a services first. For that, it needs to be run from elevated command prompt for the first time. This is a one-time installation step.
To make psexec work, you need to accept the EULA prompt. This is done per session/user. So even if you run psexec -accepteula in your command prompt, it doesn't help when Jenkins service (running as Local System in session 0) tries to use it. Therefore, you have to place that into the Jenkins job, along with the command. Technically, it only needs to be there once, and can be removed afterwards, but it definitely doesn't hurt to keep it there.
I've used cmd /k and running this command from my local cmd prompt to debug. This is what made me realize I couldn't find a way to escape the spaces (tried various quoting), so had to resort to short file names. Note that short file names are not required, this is just to escape spaces.
no its not-
plus any UI interactions requires you to run Jenkins as Java web start rather than a service or you can not interact with UI elements.

Starting independent batch files through ssh and process ownership

I've used batch files for many things in the past... but I've always had this problem. I'm sorry if this is a repeat question, I'm not entirely sure I know how to phrase it for searching purposes. The problem is this:
1) Batch file starts some process.
2) command window closed by user.
3) process started by batch file ends.
I imagine this is due to the fact that the started process is "called" by the batch file, and is thus it's child. Specifically what I'm trying to do is login to a server through ssh, run a batch file located on that server which then starts a java program. I need the batch to either stay open, or allow the java program to own itself somehow. That way, when I leave the SSH session, the program will continue to run. Any ideas how I can do this?
I'm running a windows XP x64 server with MobaSSH.
You could try using the psexec tools from sysinternals.
Some possible helpful commands:
at
schtasks
sc
wmic
I'm not sure that any of the above commands will be of any help, but I think they're worth checking out.
Question is not clear, but looks like what you are looking for is a way to "detach" the script from the terminal so that it will continue to run even when the terminal is closed.
You can do:
nohup <your-script> &
Or:
<your-script> &
disown

How can I run multiple Perl scripts on Windows without opening separate command windows?

I have as many as ten Perl scripts to run on a Windows server. Is there something better than opening a new prompt for each script and having ten windows open on your server?
You could run them as services.
Look into Win32::Daemon.
Run each program in the background. For this, you only need one prompt window. Use the start command.

Resources