You could check out Script_ClearSpam to figure this out, but here is a snippet of what you are looking for:
//loop through all bricks
%groupCount = MainBrickGroup.getCount();
for(%i = 0; %i < %groupCount; %i++)
{
%group = MainBrickGroup.getObject(%i);
%count = %group.getCount();
for(%j = 0; %j < %count; %j++)
{
%brick = %group.getObject(%j);