Home > Net >  Powershell Combine two objects on $null
Powershell Combine two objects on $null

Time:01-01

I want to combine two PowerShell objects. For each $tag1 field that is $null, the equivalent value from $tag2 should be used

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

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

The output should be :

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

CodePudding user response:

Your input object are hashtables:

  • Use the .GetEnumerator() method to send a hashtable's entries as key-value pairs through the pipeline.

  • The intrinsic .Where() method allows you to filter in those entries whose value is $null.

  • The intrinsic .ForEach() method then allows you to update those entries based on the corresponding value in hashtable $tag2.

$tag1.GetEnumerator().
  Where({ $null -eq $_.Value }).
  ForEach({ $tag1[$_.Key] = $tag2[$_.Key] })
  • Related