PowerShell v5 classes and DefaultDisplayPropertySet

Welcome Forums General PowerShell Q&A PowerShell v5 classes and DefaultDisplayPropertySet

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

 
Participant
1 year ago.

  • Author
    Posts
  • #87212

    Participant
    Points: 1
    Rank: Member

    At the end of the following code, I am using DefaultDisplayPropertySet to display only specific properties. Although this works perfectly, running this code within the foreach loop seems excessive. Without resorting to using ps1xml files, is it possible to define the default display properties without doing on each object, for example on the class? Thanks.

    foreach ($Object in $Objects) {

    #Store desired properties in the new object
    $objDetails = [objInfo]::new() #the class is defined earlier, of course
    $objDetails.Prop1 = $Object.Prop1
    $objDetails.Prop2 = $Object.Prop2
    $objDetails.Prop3 = $Object.Prop3
    $objDetails.Prop4 = $Object.Prop4
    $objDetails.Prop5 = $Object.Prop5

    #Set the default properties to be displayed
    $defaultProperties = @('Prop1', 'Prop2', 'Prop3')
    $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet', [string[]]$defaultProperties)
    $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
    $objDetails | Add-Member MemberSet PSStandardMembers $PSStandardMembers

    Write-Output $objDetails
    }

  • #87220

    Participant
    Points: 0
    Rank: Member

    This might work: Define a masterobject outside the loop and then use masterobject.copy inside the main loop to create a new object

    • #88244

      Participant
      Points: 1
      Rank: Member

      OK, your idea worked simply by using the following outside the loop (zero points to me for over-thinking it!):

      $objMaster = [HMASQLDbDetails]::new()
      $defaultProperties = @('Prop1', 'Prop2', 'Prop3', 'CompatibilityLevel')
      $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet', [string[]]$defaultProperties)
      $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
      $objMaster | Add-Member MemberSet PSStandardMembers $PSStandardMembers

      and then using this code inside the loop:
      $objMyObject = $objMaster
      $objMyObject.Prop1 = "whatever"
      $objMyObject.Prop2 = "whatever"
      $objMyObject.Prop3 = "whatever"
      etc.

      Thanks for the help.

  • #87524

    Participant
    Points: 1
    Rank: Member

    Thanks for the response. Unfortunately, I'm not sure how to do what you're suggesting. I don't see a Copy method on the object.

The topic ‘PowerShell v5 classes and DefaultDisplayPropertySet’ is closed to new replies.