Home > database >  How can I run a pipeline with variables in a background task in Powershell?
How can I run a pipeline with variables in a background task in Powershell?

Time:08-26

I'm trying to run two large sort processes simultaneously. So far, I've been unable to run one of these processes in the background.

Here's what I'm doing:

Get-Content $attfile |Sort-Object { 
  [datetime]::ParseExact($_.Substring(0, 23), 'dd/MM/yyyy HH:mm:ss.fff', $null) 
} | out-file -filepath "$new" -Encoding ascii 


Get-Content $navfile | Sort-Object { 
  [datetime]::ParseExact($_.Substring(0, 23), 'dd/MM/yyyy HH:mm:ss.fff', $null) 
} 2> $null | out-file -filepath "$navnew" -Encoding ascii

I would like to run the first sort in the background so that I don't have to wait for the first sort to finish. How can I do this? I find the powershell documentation of Start-Job very confusing.

CodePudding user response:

You can pass arguments to the job's scriptblock via the -ArgumentList parameter:

$job = Start-Job -ScriptBlock {
  param($inPath,$outPath)

  Get-Content $inPath |Sort-Object { 
    [datetime]::ParseExact($_.Substring(0, 23), 'dd/MM/yyyy HH:mm:ss.fff', $null) }
  } |Out-File $outPath
} -ArgumentList $attfile,$new

# do the other sort in foreground here ...

$job |Wait-Job

if($job.State -eq 'Completed'){
  # background sort succeeded, you can read back $new now
}
  • Related