Search code examples
powershellazure-powershellintunewindows-defendermicrosoft-graph-intune

Filtering Powershell result in For Each statement


I've written (or trying to write atleast) a simple script to get all Microsoft Intune Defender Policies that are a assigned to a specific Azure AD group.

The scripts gets all Defender policies, finds the group ID linked to those policies and then it gets the actual name using Get-AzureADGroup.

Now I need to find a way to only show the policy that matches a specific group name (hard-coded). At the top of the script I have a variable with the group name. I just can't find a way on how to filter all the $intent(s) to only show the ones linked to the group name variable.

Connect-MSGraph -ForceInteractive
Update-MSGraphEnvironment -SchemaVersion beta
Connect-MSGraph
Connect-AzureAD

$groupname = "group-name-here"

$intents = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/intents" | Get-MSGraphAllPages


 foreach ($intent in $intents) {
        $PolicyID = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/intents/$($intent.Id)/assignments"
        $AssignmentGroupIDs = $PolicyID.value.target.groupID

            foreach ($AssignmentGroupID in $AssignmentGroupIDs) {
                $AssignmentGroupName = Get-AzureADGroup -ObjectId $AssignmentGroupID

            }
        }


Write-Host "Number of policies found: $($intents.Id.Count)" -ForegroundColor cyan
Write-Host $AssignmentGroupName.DisplayName
Write-Host $intent.displayName

Solution

  • Any value you create and don't assign to a variable will be part of the script block's output. That means you can do things like this:

    $result = foreach (...) {
         if (condition) {
             $value
         }
    }
    

    and $result will contain all the $values from the loop.

    In context (untested, but you get the idea):

    $matchingIntents = foreach ($intent in $intents) {
        $PolicyID = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/intents/$($intent.Id)/assignments"
        $AssignmentGroupIDs = $PolicyID.value.target.groupID
        foreach ($AssignmentGroupID in $AssignmentGroupIDs) {
            $AssignmentGroupName = Get-AzureADGroup -ObjectId $AssignmentGroupID
            if ($AssignmentGroupName -eq $groupname) {
                $intent
                break
            }
        }
    }