运行一段时间之后,我的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
请问是否有关于原因的想法?
谢谢 !
虽然错误消息并不总是有用,但这个消息是:
它告诉您,您尝试与$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)