Enumerating over objects

Looping Through a Collection of Objects.

There are two ways of enumerating over objects. One may be considered easier than the other. Nevertheless the two ways are shown below.

1.

Using a WHILE loop and GetEnumerator.

$lines = @('a', 'b', 'c', 'd', 'e', 'f');
$enumerator = $lines.GetEnumerator();

while ($enumerator.MoveNext()) {
    $enumerator.Current;
}

2.

Using a foreach loop.

$lines = @('a', 'b', 'c', 'd', 'e');
foreach ($item in $lines) {
   Write-Host $item;
}

See also

Foreach-Object Cmdlet

Advertisements
This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s