Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird PowerShell problem: [ref] cannot be applied to a variable that does not exist

My Powershell script exited with "[ref] cannot be applied to a variable that does not exist" after running a while (it actually worked for a while)

The code snippet is something like

function outputData(...) {
    $data = $null
    if ($outputQueue.TryTake([ref] $data, 1000) -eq $false) {
        continue
    }
    Write-Host $data
}

The detail errors thrown at the end are as below:

[ref] cannot be applied to a variable that does not exist.
At C:\Program Files\mfile.ps1:1213 char:13
+         if ($outputQueue.TryTake([ref] $data, 1000) -eq $ ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (data:VariablePath) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : NonExistingVariableReference

May i ask if any thoughts about the cause ?

Thanks !

like image 866
Ken Chen Avatar asked Feb 27 '26 07:02

Ken Chen


1 Answers

While error messages aren't always helpful, this one is:

It tells you that the $data variable you're trying to use with [ref] must already exist, i.e., must have been created explicitly, which in PowerShell means:

  • creating it by assigning a value to it - even if that value is $null,
  • or using New-Variable to create it.

A simplified example:

$data = $null # create variable $data

# OK to use $data with [ref], now that it exists.
# $data receives [int] value 10 in the process.
[int]::TryParse('10', [ref] $data) 
like image 97
mklement0 Avatar answered Mar 02 '26 05:03

mklement0