PoshCode Archive  Artifact [0102866bf1]

Artifact 0102866bf11f1a2fe9b5bc41ccbc0f95c4b082e8858b8ed00e4bfcd628c75ebf:

  • File Join-Objects.ps1 — part of check-in [18cb311896] at 2018-06-10 12:58:56 on branch trunk — Performs a simple join of all properties from two objects. Now supports scriptblock evaluation: (user: Joel Bennett size: 1510)

# encoding: ascii
# api: powershell
# title: Join-Objects
# description: Performs a simple join of all properties from two objects. Now supports scriptblock evaluation:
# version: 2.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Join-Object
# x-poshcode-id: 1596
# x-derived-from-id: 1818
# x-archived: 2016-07-10T18:53:13
# x-published: 2010-01-20T09:46:00
#
# ls | Join-Object { $_ | Select BaseName }  { $_.LastWriteTime } | ft -auto
#
#function Join-Object {
   Param(
      [Parameter(Position=0)]
      $First
   ,
      [Parameter(Position=1)]
      $Second
   ,
      [Parameter(ValueFromPipeline=$true)]
      $InputObject
   )
   BEGIN {
      if($First -isnot [ScriptBlock]) {
         $Out1 = $First
         [string[]] $p1 = $First | gm -type Properties | select -expand Name
      }
   }
   Process {
      if($First -is [ScriptBlock]){
         $Out1 = $InputObject | &$First
         [string[]] $p1 = $Out1 | gm -type Properties | select -expand Name
      }
      
      $Output = $Out1 | Select $p1
      
      if($Second -is [ScriptBlock]) {
         $Out2 = $InputObject | &$Second
      } elseif(!$Second) {
         $Out2 = $InputObject
      } else {
         $Out2 = $Second
      }
      
      foreach($p in $Out2 | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
         Add-Member -in $Output -type NoteProperty -name $p -value $Out2.($p)
      }
      $Output
   }
#}