Replace the foreach on userprofiles with this while($profile1.MoveNext())
and $profile1.Current
will return you the current user profile. Sample
$upm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$iterator = $upm.GetEnumerator()
while($iterator.MoveNext())
{
Write-Host $iterator.Current.DisplayName
}