Powershell ForEach Loop Statement Tutorial with Examples

RSS
FACEBOOK
FACEBOOK
PINTEREST
PINTEREST
LINKEDIN
INSTAGRAM

ForEach is a term used to use iterate or loop over the given list, array or collection of the objects, strings, numbers etc. Forach is very popular loop mechanism where we can use different cases like loop through files, Numbers, Strings, Processes etc. Powershell version 4.0 brings some performance improvements to the ForEach loop.

Syntax

Foreach statement has the following syntax where we use ITEM, COLLECTION and CODE-BLOCK.

  • ITEM is a single value or object which changes over each iteration.
  • COLLECTION is an array, collection, list of values or objects like 1,2,3,4
  • CODE BLOCK is the block where the real operation runs which generally uses ITEM. This block can be single or multiple lines.

ForeachThrough An Array Of Strings

In a simple way, we can iterate over the given list of the string array. We iterate over array named cities which holds multiple city names. We will print each city name with the echo command like below.

ForeachThrough An Array Of Strings
ForeachThrough An Array Of Strings

Foreach Through An Collection Of Numbers

In the previous example, we have looped over a given list of strings. We can also iterate or loop through a list of numbers. We will create an array named numbers and iterate over each item in this number array.

Foreach Through An Collection Of Numbers
Foreach Through An Collection Of Numbers

$_ Usage

When using some cmdlets to redirect the output of cmdlet to the Foreach we can use $ for each item or object. For example, if we use Get-Process cmdlet each item or process will be assigned to the $ in each iteration. We can specify the attribute like Name $.Name  and print like below.

LEARN MORE  C - Arrays

$_ Usage
$_ Usage

We can also print multiple attributes in foreach by delimiting them with comma.

$_ Usage
$_ Usage

Foreach Through Files

We can also loop through files by using Get-ChildItem cmdlet. Get-ChildItem will list files and folders like dir MSDOS command. This output will be written to console with the Echo command.

Foreach Through Files
Foreach Through Files

Foreach Through Specific File Extensions Like Bat

We can specifically list the specified extension. The extension will generally provide the file type like text, avi, mkv, mp3, doc etc. In this example, we will list only *.bat or Bat files.

Foreach Through Specific File Extensions Like Bat
Foreach Through Specific File Extensions Like Bat

We can see that only files like test.bat and autoexec.bat will be listed.

Foreach Over CSV File

CSV files are used to store text data in a structured manner. We can easily foreach in each line of a CSV file like below. In this example, we will read an IP CSV file and provide to the foreach to print Powershell console.

RSS
FACEBOOK
FACEBOOK
PINTEREST
PINTEREST
LINKEDIN
INSTAGRAM