PowerShell 后台作业(同时有多个 .cmd 文件)

PowerShell background jobs (multiple .cmd files at the same time)

我正在尝试在 PowerShell 中同时同步不同的任务,因为每个任务大约需要 2-4 小时。我现在拥有的脚本只是一个接一个地处理每个任务。我知道 PowerShell 中有一个名为 background jobs 的选项。有没有办法转换以下代码,使其同时处理多个 .cmd 文件?

$handler_button1_Click= 
{
$answer= $finalcheck.popup("text",0,"text",4)
If($answer-eq 6) {
   [Windows.Forms.MessageBox]::Show("text", "Information", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
   $listBox1.Items.Clear();    
    if ($checkBox1.Checked)    { 
    Try{ 
    & K:\sample.cmd
    }catch [System.Exception]{
    $listBox1.Items.Add("Error")}
    }

    if ($checkBox2.Checked)    { 
    Try{ 
    & K:\sample2.cmd
    }catch [System.Exception]{
    $listBox1.Items.Add("Error")}
    }

您可以使用 Start-Job:

$job = Start-Job { & K:\sample.cmd }

此时您可能需要添加一些代码来观察您已启动的作业的状态。您可以定期检查 $job.State.

在此基础上,如果已经 运行.

,您可能会拒绝开始一份相同类型的工作

除了 Start-Job,您还应该看看:

  • Get-Job - 获得任何工作(运行 或其他)
  • Receive-Job - 返回结果
  • Remove-Job - 完成作业后将其删除。
  • Stop-Job - 在需要终止作业时停止作业。