我想启动后台作业并将其进程ID捕获到.pid文件中。我能够使用Start-Process执行以下操作:
Start-Process C:\process.bat -passthru | foreach { $_.Id } > start.pid
现在,我想用Start-Job包装Start-Process,在后台运行它,如下所示:
$command = "Start-Process C:\process.bat -passthru | foreach { $_.Id }"
$scriptblock = [Scriptblock]::Create($command)
Start-Job -ScriptBlock $scriptblock
不幸的是,这不起作用,Receive-Job给了我以下错误:
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覆盖。
任何线索都非常欢迎!
答案 0 :(得分:3)
这是因为在使用双引号时正在扩展变量。如果你想保留$ _,那么你需要使用单引号。
$command = 'Start-Process C:\process.bat -passthru | foreach { $_.Id }'
$scriptblock = [Scriptblock]::Create($command)
Start-Job -ScriptBlock $scriptblock