ref cannot be applied to a variable that does not exist. (Using a global variable in a ForEach-Object -Parallel loop)

14 views Asked by At

I have a function that utilizes a ForEach-Object -Parallel loop. I am trying to report progress to a dialog. Here's the relevant code (I've removed irrelevant code):

In my param block:

[Parameter(Mandatory = $false)]
[System.Management.Automation.ScriptBlock]
$ProgressReporter

The loop:

# Define the total number of tasks
$totalTasks = $List.Count
$global:taskIndex = 0

$List | ForEach-Object -Parallel {

    $totalTasks          =  $Using:totalTasks
    $ProgressReporter    =  $Using:ProgressReporter

    # Inside each parallel block, calculate progress and report it
    $currentTaskIndex = [System.Threading.Interlocked]::Increment([ref]$global:taskIndex)
    [int] $progress = [math]::Round(($currentTaskIndex / $totalTasks) * 100)

    $ProgressReporter.Invoke($progress)
    
    ...

When I run this code, I get:

Line |
  17 |              $currentTaskIndex = [System.Threading.Interlocked]::Incre …
     |              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | [ref] cannot be applied to a variable that does not exist.

I don't understand this error, as I do explicitly define it immediately before the loop: $global:taskIndex = 0.

Can someone identify what I'm doing wrong? Any help would be greatly appreciated.

0

There are 0 answers