Converting VBScript's For Each...Next Statement

Definition: Repeats a group of statements for each element in an array or collection.

For Each…Next

A For Each loop is designed to automatically run through all the items in a collection or array. In Windows PowerShell you can iterate all the items in a collection by using the ForEach-Object collection (or its more-commonly-used alias, foreach). To set up a For Each loop in Windows PowerShell, call foreach followed by two parameters:

  • The collection you want to iterate. This value must be enclosed in parentheses.

  • The action you want to perform on each item in that collection. This value must be enclosed in curly braces: {}.

For example, the following command sets up a For Each loop that uses the Get-ChildItem Cmdlet to return a collection of all the files found in the folder C:\Scripts. Note the syntax that must be used: ($i in get-childitem c:\scripts). Obviously this is different than what you are used to. After all, in VBScript you “kick off” a For Each loop using code similar to this:

For Each i in colItems

However, in Windows PowerShell you call foreach and then kick things off using code like this:

($i in $colItems)

After specifying the loop condition the command then indicates the behavior to be performed:

{$i.extension}

This simply says, “For each item ($i) in the collection, echo back the value of the Extension property.”

Here’s the actual command:

foreach ($i in get-childitem c:\scripts) {$i.extension}

You should get back something similar to this, depending on the files found in C:\Scripts:

.gif
.xls
.xls
.txt
.txt
.xls
.ps1
.ps1
.zip
.vbs
.txt
.ppt

Return to the VBScript to Windows PowerShell home page