Object copy

Welcome Forums General PowerShell Q&A Object copy

This topic contains 4 replies, has 4 voices, and was last updated by

 
Inactive
3 years, 9 months ago.

  • Author
    Posts
  • #21576

    Inactive
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member
    $S=Get-Service DNS*
    $S | Add-Member MyName 'Admin'
  • #21583

    Keymaster
    Points: 7
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    If for some reason you really do want to create a new object with all the same properties, piping the original object to Select-Object -Property * 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

    Inactive
    Points: 0
    Rank: Member

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

The topic ‘Object copy’ is closed to new replies.