Copying Properties to another Object

I had a thought today that it would be interesting to write a function to copy properties from one object to another. Specifically I was thinking about doing a join operation on two arrays and that it would be good to be able to say “copy these properties from the object on the right to the object on the left”. Since I couldn’t think immediately about how that function would look, I wrote it. Here’s the code I came up with:

function Copy-Property{
[CmdletBinding()]
param([Parameter(ValueFromPipeline=$true)]$InputObject,
      $SourceObject,
      [string[]]$Property,
      [switch]$Passthru)

      $passthruHash=@{Passthru=$passthru.IsPresent}
    
      $propHash=@{}
      $property | Foreach-Object {
                    $propHash+=@{$_=$SourceObject.$_}
                  }
      $inputObject | Add-Member -NotePropertyMembers $propHash @passthruHash
    }

And here’s a screenshot showing it in use.
CopyProperty

I haven’t “finished” the function because I’m not sure that I’m ever going to use it, but here are a few things to notice:

  • This is an advanced function.
  •  I didn’t enable -Whatif and -Confirm because Add-Member doesn’t
  • I’m using splatting to flow the -Passthru switch along to Add-Member
  • Add-Member allows a hashtable of property names and values, just like New-Object does. I learned that today!
  • I’ve allowed pipeline input, but you only get one object to copy from 🙁
  • I could have called Add-Member for each property, but I like doing it this way better.  I might change my mind on that.

So, this was a fun exercise.  I don’t think that it will be useful in anything, but it was fun to write so I thought I’d share.

Having a blast in PowerShell!

–Mike

 

P.S.  I know that there are several implementations of Join-Object out there.  I will probably end up using one of them.

2 Comments

  1. Even if the function it self is not spey useful, I got a few ideas from it. Specifically the way you used the passthru parameter. I was just trying to figure out how I would do that in a function I’m working on.

Comments are closed.