1

I have a powershell object array like this

$EdosContainers= @([pscustomobject]@{Container='FoundationObjectStoreConfigMetadata';PartitionKey='/templateName'}
       [pscustomobject]@{Container='FoundationObjectStoreObjectInformation';PartitionKey='/processExecutionId'}
       [pscustomobject]@{Container='FoundationObjectStoreObjectMetadata';PartitionKey='/processExecutionId'}
       [pscustomobject]@{Container='FoundationObjectStoreConfigMetadataTransfomed';PartitionKey='/templateName'})

But I need to check whether a given value exists in the array or not in the container attribute.

I know we can use -contains method for checking the existence of an item in array. But since mine is an object array how can we accomplish this?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132

1 Answers1

3

You can take advantage of member-access enumeration, which extracts all .Container property values from the array's elements by directly applying the property access to the array, allowing you to use -contains:

# -> $true
$EdosContainers.Container -contains 'FoundationObjectStoreConfigMetadataTransfomed'

If you want to avoid the implicit creation of an array with all .Container values, use the intrinsic .Where() method:

[bool] $EdosContainers.Where(
  { $_.Container -eq 'FoundationObjectStoreConfigMetadataTransfomed' }, 
  'First'  # Stop, once a match is found.
)

While this is more memory-efficient than using member-access enumeration, it also noticeably slower with large arrays.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • My pleasure, @SandeepThomas. I later saw that Omkar76 suggested that your question is a duplicate, which I think is correct, so I'm closing it as such. – mklement0 Aug 10 '22 at 15:36