title: Sharing variables between jobs
body: <p>I have a powershell script which is supposed to run a background job until the user decides it should end. The background job is this Script Block:</p>
  
  <pre><code>$block = 
      {
           param(
              [Parameter(Mandatory = $true, Position = 0, valueFromPipeline = $true)]
              $Counters,
              [Parameter(Mandatory = $true, Position = 1, valueFromPipeline = $false)]
              [ref]$killSwitch,
              [Parameter(Mandatory = $false, Position = 2, valueFromPipeline = $false)]
              [long]$SampleInterval = 1000
           )
          [System.Diagnostics.Stopwatch]$sw = New-Object System.Diagnostics.StopWatch
          $sw.Start()
          $last = 0
          $report = New-Object PSObject
          $report | Add-Member -MemberType NoteProperty -Name Start -Value ([DateTime]::Now)
          while(!$killSwitch)
          {
              if($sw.ElapsedMilliseconds -gt $last + $SampleInterval)
              {
                  $rec = Get-CounterSample -counters $Counters
                  $report | Add-Member -MemberType NoteProperty -Name $sw.ElapsedMilliseconds -Value $rec
                  $last = $sw.ElapsedMilliseconds
              }
          }
          $report | Add-Member -MemberType NoteProperty -Name End -Value ([DateTime]::Now)
          return $report  
      }
  </code></pre>
  
  <p>As you can see, I'm trying to pass in a boolean (<code>$killSwitch</code>) as a way of stopping the <code>While</code> loop once the user/ caller is done. I call it in the following way:</p>
  
  <pre><code>[bool]$kill = $false
  $job = Start-Job -Name twProcMon -ScriptBlock $block -ArgumentList $Counters, ([ref]$kill), $SampleInterval
  Read-Host
  $kill = $true
  Wait-Job $job
  Receive-Job $job
  </code></pre>
  
  <p>I get an error:</p>
  
  <blockquote>
    <p>Cannot process argument transformation on parameter 'killSwitch'.
    Reference type is expected in argument.</p>
  </blockquote>
  
  <p>How do I pass a bool by reference to a code block, such that I can kill the while loop from outside the job? Is it possible?</p>