doenoe
doenoe

Reputation: 322

Foreach loop in a if statement

Wrote a small script to check if certain AD groups exists. For some reason it wont loop through the given array. It only writes the first value of the array to the console. When I put a breakpoint on:

foreach ($item in $SecGroupNames)

I see $secGroupNames being filled with the gives values, can anyone help me out? Can't figure it out for this one.

Code:

Import-Module activedirectory
$SecGroupNames = @(  
                     "DB_DATAREADER",
                     "DB_DATAWRITER",
                     "DB_OWNER",
                     "SQL_Public",
                     "SQL_SA",
                     "SQL_SecurityAdmin"
                  )

    foreach ($item in $SecGroupNames)
      {   
        If (Get-ADGroup $item)
        {     
            Write-Host -ForegroundColor Yellow "$item Exists!"
            return $true; 
        }
        else
        {
            Write-Host -ForegroundColor Green "$Item Does not exist, Do something!" 
            return $false;
        }
      }

Output:

PS C:\Scripts\CreateOUgroups> C:\Scripts\CreateOUgroups\FunctionCheckSecurityGroup.ps1
DB_DATAREADER Exists!
True

Upvotes: 1

Views: 17089

Answers (1)

dstarkowski
dstarkowski

Reputation: 337

It's because of return statements. It causes the script to return value and end execution in the first loop pass.

If you want to return multiple values from script or function, use Write-Output instead of return.

foreach ($item in $SecGroupNames)
{   
  if (Get-ADGroup $item)
  {     
    Write-Host -ForegroundColor Yellow "$item Exists!"
    Write-Output $true;
  }
  else
  {
    Write-Host -ForegroundColor Green "$item Does not exist, Do something!" 
    Write-Output $false;
  }
}

Upvotes: 3

Related Questions