arrayspowershellmember-access-enumeration

Using contains operator for array of objects in powershell


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?


Solution

  • 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.