问题描述
我想启动一个后台作业并将它的进程 ID 捕获到一个 .pid 文件中.我能够使用 Start-Process 来做到这一点,如下所示:
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
现在,我想用 Start-Job 包装 Start-Process,以便在后台运行它,如下所示:
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
不幸的是,这不起作用,Receive-Job 给了我以下错误:
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
看起来 $_ 变量有问题.也许它会被 Start-Job 覆盖.
Looks like it's something wrong with the $_ variable. Maybe it gets overwritten by the Start-Job.
非常欢迎任何线索!
推荐答案
那是因为使用双引号时变量被扩展了.如果要保留$_,则需要使用单引号.
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
这篇关于Powershell:捕获后台作业的进程 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!