将 return 值分配给变量中断递归

Assigning return value to variable breaks recursion

我正在使用递归函数将两个 JSON 对象和 运行 比较为一个 st运行ge 问题。我的递归工作正常......直到我将递归调用的结果分配给一个变量。如果我只是进行函数调用,则递归起作用,并且所有成员都被迭代。当存在赋值时,递归中断并且仅迭代对象的第一级。

(带箭头的线表示递归调用)

为什么这不起作用?

function Compare-Objects() {
  [CmdletBinding()]
  Param(
    $Current,
    $Expected
  )
  foreach ($Property in $Expected.PSObject.Properties) {
    $Property.Name + " : " + $Property.TypeNameOfValue
    if ($Property.TypeNameOfValue -like "*PSCustomObject") {
->    $Match = Compare-Objects -Current $Current.$($Property.Name) -Expected $Expected.$($Property.Name)
    }
    elseif ($Property.TypeNameOfValue -like "*Object[[][]]"){
      # Compare-Arrays -Current $Current.$($Property.Name) -Expected $Expected.$($Property.Name)
    }
    else {
      if ($Property.Value -like "*enums*") {
        $Expected.$($Property.Name) = Invoke-Expression -Command $Expected.$($Property.Name)
      }
      if ($Current.$($Property.Name) -ne $Expected.$($Property.Name)) {
        return $false
      }
    }
  }
  return $true
}

使用变量赋值 ($Match = ...) 的一个副作用是被赋值的值不再受 PowerShell 的 , i.e. it isn't emitted to the statement's / function's / script [block]'s success output stream 影响,因此不再影响其“return价值”。

换句话说:你的递归工作正常,你只是不小心抑制了嵌套调用的输出。

如果要将命令输出分配给变量将分配的值通过传递给成功输出流,将其包含在(...),即使用 ($Match = ...)


另外,如果您想绕过成功输出流,例如用于打印不干扰 data 输出的状态/调试信息:

  • 您可以使用 Write-Verbose and Write-Debug 等 cmdlet 写入 PowerShell 的 other 输出流,只有当 请求.

  • 相比之下,Write-Host cmdlet - 主要用于 to-display 输出,通常包括格式化(着色) - 产生可见默认输出 .