奇怪的PowerShell问题:[ref]不能应用于不存在的变量

问题描述 投票:2回答:1

运行一段时间之后,我的Powershell脚本退出并且“[ref]无法应用于不存在的变量”(它实际上工作了一段时间)

代码片段就像

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

最后抛出的细节错误如下:

[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

请问是否有关于原因的想法?

谢谢 !

powershell pass-by-reference
1个回答
2
投票

虽然错误消息并不总是有用,但这个消息是:

它告诉您,您尝试与$data一起使用的[ref]变量必须已经存在,即必须已明确创建,这在PowerShell中意味着:

  • 通过为其赋值来创建它 - 即使该值是$null
  • 或使用New-Variable创建它。

一个简化的例子:

$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) 
© www.soinside.com 2019 - 2024. All rights reserved.