clanahan
clanahan

Reputation: 13

Powershell: Backgrounding command causes it not to work

My script stores a bunch of External application commands from an app like so

$app1 = get-command "C:\Where\Command\Located.exe"

Then I call it with

& $app1 -S -P 9000

(where -S -P and 9000 are parameters as I'd pass them in a cmd.exe shell). Up to here everything works perfectly. However, I want to run this as a background task and here's where I begin running into trouble.

Start-Job -ScriptBlock { & $app1 -S -P 9000 }

fails with "The expression after '&' in a pipeline element produced an invalid object." I've searched google for about two days and everything I've tried seems to be for naught. Enclosing parameters in @() and trying to splat them out, Invoke-Expression, Invoke-Command, Invoke-Item (still unclear as to what these are all doing). I've also tried converting the whole command to a string and then calling Invoke-Expression within the start job but it doesn't seem to be working either. So this question is resources to understand when all these things are appropriate to use and why it doesn't work as soon as I pass it to a background job.

Upvotes: 1

Views: 2871

Answers (1)

manojlds
manojlds

Reputation: 301087

Try passing the $app1 variable to the script block:

Start-Job -ScriptBlock {param($app1) & $app1 -S -P 9000 } -ArgumentList $app1

Note that instead of

$app1 = get-command "C:\Where\Command\Located.exe"

you can also just have

$app1 = "C:\Where\Command\Located.exe"

Upvotes: 1

Related Questions