【问题标题】:PowerShell Hash table updates apply to all entriesPowerShell 哈希表更新适用于所有条目
【发布时间】:2018-09-12 12:04:52
【问题描述】:

我正在尝试更新我找到值的哈希表条目(内容,它是一个数组) - 但是当我尝试为 $_ 设置值时,它适用于整个哈希 ($hash) 中的所有条目。

$ContentArray = @($null, $null)
$Comparison | Add-Member -MemberType NoteProperty -Name "Content" -value $ContentArray

    If($GetAdvancedData -eq "true"){
    $Hash| ForEach-Object{
    If ($_.VarianceType -ne  "Missing")
            {
            $_.Item
            $id = $_.id[0]
            $elem = $_.elementName
            Write-debug "Checking $elem"
            Write-debug "Checking for version $id"
            try{
                $content = Get-VersionContent -FilteredVersionID $id
                Write-debug "Content found"
                Write-debug "$content"
                # Various tests to try and set the value:
                #ForEach ($Key in $Hash.GetEnumerator() | Where-Object {$_.id -eq $id}){$Key.Content[0] = $content}
                #$Hash.Content[0] = "$content" | Where-Object {$Hash.id[0] -eq $id}
                #$Hash.DiffType = "Content"| Where-Object {$_.id[0] -eq $id}
                # $_.content.SetValue("$content","0")
                $_.Content[0] = $content
                # Reset $content to Null
                $content = $null
                }
            catch
            {
                Write-debug "No content found"
            }
            }
        }

我尝试通过基于另一个键值的 where 子句设置它,使用 SetValue,并简单地执行 = 语句,但在每种情况下,它都将整个哈希表内容设置为 $content - 我觉得我必须遗漏了一些明显的东西,但我不明白为什么(如果我使用 PowerShell ISE 并调试 $_ 仅返回 ForEach 循环中的单个记录)

【问题讨论】:

    标签: powershell hashtable


    【解决方案1】:

    一个愚蠢的错误-

    $Hash.GetEnumerator() | Where-Object {$_.id[0] -eq $id} | foreach{$_.Content = $content,$null}
    

    帮我搞定了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2021-11-19
      • 2014-07-05
      • 1970-01-01
      • 2014-11-21
      • 2021-06-01
      • 1970-01-01
      相关资源
      最近更新 更多