Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

For Each

2010-10-08

The ForEach keyword is used to iterate through a collection of objects that you have a reference to. You can get a reference to a collection by calling a function or by declaring and initializing an array. This example will give you an array of strings in a variable called $arr:

$arr = "A", "B", "C"

If you want to do something with each element in the array, the ForEach keyword is used. This example just writes out each element:

ForEach ($x In $arr) {Write-Output $x}

Sending data to the next object in the pipeline (that will be displayed in the console window if not picked up) is the default behaviour, so Write-Output can be ommited in this case.

ForEach ($x In $arr) {$x}

The result will be:

A
B
C

This works like the For Each keyword in Visual Basic, so you could do something with each element within the curly brackets. This will display the lower case version before the upper case version of each element:

ForEach ($x In $arr) {$x.ToLower(); $x}

The result:

a
A
b
B
c
C

The ForEach-Object cmdlet can iterate through any collection of objects that is piped in. It works in the same way, but now you don’t have to specify the collection or the variable that will represent the elements. The collection is whatever is piped in, and the variable that represent the elements (I used $x in my examples) will be the “this token” ($_).

This will add all running processes to the pipeline:

Get-Process

And this will give you the posibility to reference each process.

Get-Process | ForEach-Object { Write-Host $_.Name }

Get-Process cmdlet will send some process objects to the pipeline, they are picked up by the ForEach-Object cmdlet, and the names of the processes are sent to the pipeline. Since nothing picks up the names, the names will be displayed.

Categories: PowerShell

One response to “For Each”

  1. […] This post was mentioned on Twitter by Anders Hesselbom, Jim Poshible. Jim Poshible said: RT @ahesselbom: PowerShell: For Each. http://bit.ly/bNNH2A […]

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips