Object copy

This topic contains 4 replies, has 4 voices, and was last updated by Profile photo of  Anonymous 2 years, 5 months ago.

  • Author
  • #21576
    Profile photo of

    Hi Team,
    How can I copy all the properties of an object ( in the below example $S=TypeName: System.ServiceProcess.ServiceController) to a PSCustom object by keeping some more additional properties of its properties. The below is the example..

    $S=Get-Service DNS*
    $obj = new-object -TypeName PSObject -property @{MyName='Admin'}

    Now I need another Variable | object which contains all the $S|fl * along with $Obj|fl * ; my final target is to write-output with a single datatype.

  • #21578
    Profile photo of Sean Quinlan
    Sean Quinlan
    $S=Get-Service DNS*
    $S | Add-Member MyName 'Admin'
  • #21583
    Profile photo of Don Jones
    Don Jones

    Sean's point is correct – you don't need to copy the object. PowerShell lets you add properties (and other members) directly to any object. So you should just add them to the ServiceController. PowerShell's extensible type system (ETS) already adds numerous members to the base .NET object.

  • #21598
    Profile photo of Dave Wyatt
    Dave Wyatt

    If for some reason you really do want to create a new object with all the same properties, piping the original object to [b]Select-Object -Property *[/b] will do the trick. You'll wind up with a PSObject containing a bunch of NoteProperties, instead of whatever type the original object was.

  • #21607
    Profile photo of

    Wow. That is awesome. This is what I am looking for. Thanks Wyatt.

You must be logged in to reply to this topic.