Powershell: Background Processing ID

I want to run a background job and write it to a .pid file. I was able to do this using Start-Process as follows:

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

Now I want to migrate the Start-Process using Start-Job to start it in the background, for example:

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

Unfortunately, this does not 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

There seems to be something wrong with the $ _ variable. It may be overwritten by Start-Job.

Any hints are greatly appreciated!

+2
source share
1 answer

This is because the variable expands when using double quotes. If you want to save $ _, you need to use single quotes.

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

Source: https://habr.com/ru/post/1625856/


All Articles