What is the equivalent of 'nohup' in PowerShell?
Asked Answered
D

1

9

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.

Dc answered 11/10, 2013 at 15:30 Comment(3)
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?Berkly
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.Despond
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 to a related question for how to achieve true nohup-like behavior on Windows (and on Unix).Erastian
N
14
> 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.

Nildanile answered 11/10, 2013 at 18:24 Comment(4)
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.Nildanile
Eld, yes, that was exactly the problem I was encountering. You nailed it perfectly.Dc
Is there a way to avoid script termination in case of console window closed?Snowy
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).Hartnett

© 2022 - 2024 — McMap. All rights reserved.