Powershell在$null上合并两个对象

q3qa4bjr  于 2023-01-20  发布在  Shell
关注(0)|答案(1)|浏览(89)

我想组合两个PowerShell对象。对于每个$tag1字段为$null,应使用$tag2中的等效值

$tag1=@{'Artist'='Madonna';`
        'Title'='Like a Prayer';`
        'Genre'=$null; }

$tag2=@{'Artist'='Madonna';`
        'Title'='Like a Prayer (single version)';`
        'Genre'='Pop; }

输出应为:

$output=@{'Artist'='Madonna';`
          'Title'='Like a Prayer';`
          'Genre'='Pop; }
oyxsuwqo

oyxsuwqo1#

输入对象为hashtables

  • 使用.GetEnumerator()方法将哈希表的条目作为键-值对通过管道发送。
  • 内部.Where()方法允许您过滤那些值为$null的条目。
  • 然后,内部.ForEach()方法允许您根据散列表$tag2中的相应值更新这些条目。
$tag1.GetEnumerator().
  Where({ $null -eq $_.Value }).
  ForEach({ $tag1[$_.Key] = $tag2[$_.Key] })

相关问题