Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Capture process id of a background job

Tags:

powershell

I want to start a background job and capture it's process id into a .pid file. I was able to do it with the Start-Process as follows:

Start-Process C:\process.bat -passthru | foreach { $_.Id } > start.pid

Now, I want to wrap Start-Process with Start-Job, to run it in the background, like this:

$command = "Start-Process C:\process.bat -passthru | foreach { $_.Id }"
$scriptblock = [Scriptblock]::Create($command)
Start-Job -ScriptBlock $scriptblock

Unfortunatelly, this doesn't work and Receive-Job gives me the following error:

The term '.Id' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
+ CategoryInfo          : ObjectNotFound: (.Id:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName        : localhost

Looks like it's something wrong with the $_ variable. Maybe it gets overwritten by the Start-Job.

Any clues greatly welcome!

like image 284
daniel Avatar asked Sep 04 '25 16:09

daniel


1 Answers

That is because the variable is being expanded when using double quotes. If you want to keep the $_, then you need to use single quotes.

$command = 'Start-Process C:\process.bat -passthru | foreach { $_.Id }'
$scriptblock = [Scriptblock]::Create($command)
Start-Job -ScriptBlock $scriptblock
like image 99
boeprox Avatar answered Sep 07 '25 12:09

boeprox