typod
typod

Reputation: 49

merging objects from an array in PowerShell

I'm having a bit of a block with part of my PowerShell script.

I have an array which contains users' email addresses and their compliance state. The same user may have multiple entries in the array as they are in multiple policies.

For example:

Username: User1, State: OK
Username: User1, State: Not OK
Username: User1, State: OK
Username: User 2, State: OK
Username: User 2, State: OK

What I need to do is merge all the entries for each user and then write their overall status to the screen. If all states are OK then report OK, but if Not OK is in any of their states report Not OK. For example:

User 1 - Not OK
User 2 - OK

Any guidance is appreciated. Below is my code:

foreach ($Listing in $FullProtectionStatus) {
    if ($listing.state -eq "compliant") {
        Write-Host $Listing.userPrincipalName "compliant"
    }
    if ($Listing.state -eq "non compliant") {
        Write-Host $Listing.userPrincipalName "not compliant" -ForegroundColor Red
    }
}

Upvotes: 3

Views: 421

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200493

You could group the objects by username, then check if each group contains a "Not OK" state.

$FullProtectionStatus |
    Select-Object Username, State -Unique |
    Group-Object Username |
    Select-Object @{n='Username';e={$_.Name}}, @{n='State';e={
        $_.Group |
            Select-Object -Expand State |
            Sort-Object |
            Select-Object -First 1
    }}

Upvotes: 4

Ranadip Dutta
Ranadip Dutta

Reputation: 9272

Your validation inside foreach needs improvement because of the two If conditions. Either there will be an else condition or an elseif . Also, iterate each user and parse through the conditions.

ForEach($Listing in $FullProtectionStatus) 
{ 
    If($listing.state -eq "compliant") 
    { 
    Write-host $Listing.userPrincipalName "compliant" 
    } 
    elseif($Listing.state -eq "non compliant") 
    { 
    Write-host $Listing.userPrincipalName "not compliant" -ForegroundColor Red 
    }
}

Upvotes: 1

Related Questions