8

How can I emulate the behavior of the unix command nohup in PowerShell? That is nohup my-other-nonblocking-command. I have noticed the Start-Job command, however the syntax is somewhat unclear to me.

Joannes Vermorel
  • 8,976
  • 12
  • 64
  • 104
  • Powershell is backwards compatible, any command that works in v1 works on v2 and v3. (also v2 and v3 scripts still use the extension `.ps1`). Can you please show a example that makes you think that Start-Job or Invoke-Command would not work, and maybe post a psudocode example of how you think it could work if you knew the right commands? – Scott Chamberlain Oct 11 '13 at 16:00
  • Anything that works in PS1 will work in v2 and v3. If you explain what you actually need to accomplish, someone may be able to suggest a solution that's more in keeping with PowerShell idioms. – alroc Oct 11 '13 at 16:11
  • While the accepted answer explains the syntax of `Start-Job`, it should be noted that `Start-Job` is _not_ equivalent to the Unix `nohup` utility, as the latter ensures that the process it launches stays alive even after the launching shell exits. See [this answer](https://stackoverflow.com/a/64708000/45375) to a related question for how to achieve true `nohup`-like behavior on Windows (and on Unix). – mklement0 Nov 06 '20 at 02:57

1 Answers1

13
> Start-Job my.exe

Fails with this output:

Start-Job : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ Start-Job my.exe
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Start-Job], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartJobCommand

Try this instead:

> Start-Job { & C:\Full\Path\To\my.exe }

It will work, and you will see output like this:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
2      Job2            BackgroundJob   Running       True            localhost             & .\my.exe

I hope that is what you're looking for because your question is a bit vague.

petrsnd
  • 6,046
  • 5
  • 25
  • 34
  • The reason this works is that it creates a script block from which it executes your binary. I'm hoping your question comes from the fact that Start-Job fails unexpectedly when you just hand it a binary you'd like it to run. – petrsnd Oct 11 '13 at 18:25
  • Eld, yes, that was exactly the problem I was encountering. You nailed it perfectly. – Joannes Vermorel Oct 11 '13 at 19:18
  • 7
    Is there a way to avoid script termination in case of console window closed? – Krisz Nov 15 '19 at 19:57
  • You can run your command as a process instead using `Start-Process [my.exe] -WindowStyle hidden`. If you don't care about your program's I/O you can run it as-is, or you can specify files using the -redirect flags (see documentation). – Tom Apr 22 '22 at 04:55