Author Posts

December 7, 2017 at 12:05 am

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
}

December 7, 2017 at 12:27 am

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

December 7, 2017 at 3:11 pm

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.

December 9, 2017 at 3:25 pm

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.