Home > Enterprise >  Execute first command in foreach and if statement once
Execute first command in foreach and if statement once

Time:12-16

I want to run the first command in the foreach and if statement once and keep the second command running.

The output should be like this.

Group-1
User-1 is added in more than one group
User-7 is added in more than one group

Group-2
User-3 is added in more than one group

Group-3
User-12 is added in more than one group
User-0 is added in more than one group

i tried a lot of thing but i only get this one

Group-1
User-1 is added in more than one group
Group-1
User-7 is added in more than one group
Group-2
User-3 is added in more than one group
Group-3
User-12 is added in more than one group
Group-3
User-0 is added in more than one group

Thanks for your support.

My Code:

$aadgroupsstrings = '9a8f8f','9a739s0','8g838a'

Foreach ($group in $aadgroupsstrings) { 

$users = Get-AzureADGroupMember -ObjectId $group -All $true
$aadgroupDisplayName = get-azureadgroup -ObjectId $aadgroups | select  -ExpandProperty DisplayName


Foreach ($user in $users) {
$groups = $user | Get-AzureADUserMembership -All $true



if (($groups.DisplayName -like "Group*").count -gt 1)  { 
    Write-Host $aadgroupDisplayName -ForegroundColor Green
    Write-Host $user.DisplayName "is added in more than one group." -ForegroundColor Yellow
    }
 }
    
    }
    
    

CodePudding user response:

A counter for the users with an if- statement before the write-host of servername to make sure the servername is only shown ones before the first user name:

$counter=0
Foreach ($user in $users) {
$groups = $user | Get-AzureADUserMembership -All $true

if (($groups.DisplayName -like "Group*").count -gt 1)  { 
    if($counter -eq 0){
        Write-Host $aadgroupDisplayName -ForegroundColor Green
    }
    Write-Host $user.DisplayName "is added in more than one group." -ForegroundColor Yellow
    }
    $counter  

 }
    
    }

CodePudding user response:

I think this may just be a case of your write-host statement being in the wrong location. Give this change a try.

$aadgroupsstrings = '9a8f8f','9a739s0','8g838a'

Foreach ($group in $aadgroupsstrings) { 

    $users = Get-AzureADGroupMember -ObjectId $group -All $true
    $aadgroupDisplayName = get-azureadgroup -ObjectId $aadgroups | select  -ExpandProperty DisplayName
    Write-Host $aadgroupDisplayName -ForegroundColor Green


    Foreach ($user in $users) {
        $groups = $user | Get-AzureADUserMembership -All $true

        if (($groups.DisplayName -like "Group*").count -gt 1)  {     
            Write-Host $user.DisplayName "is added in more than one group." -ForegroundColor Yellow
        }
    }
    
}
  • Related