• Site for Newbie Windows Administrators
admincentric
  • Home
  • Active Directory
  • Hyper-V
  • PowerShell
  • Free Tools
  • Contact

PowerShell For Loop

Feb 18, 2024 Admin

In PowerShell, the for loop is used to iterate over a range of values or elements in a collection. The syntax for a for loop in PowerShell is similar to other programming languages. There are a few variations, but the basic structure is as follows:

PowerShell For Loop

Syntax

for ( <initialization> ; <condition> ; <increment>) {
# Code to be executed in each iteration
}

Here's a breakdown of each part of the for loop:

  • Initialization ( < initialization > ) : This is where you initialize a counter or set initial values. It's executed only once at the beginning of the loop.
  • Condition( < condition > ) : This is a boolean expression that is evaluated before each iteration. If the condition is true, the code inside the loop is executed; otherwise, the loop terminates.
  • Increment ( < increment > ) : This is usually an expression that modifies the loop control variable. It is executed at the end of each iteration, just before re-evaluating the condition.

Let's look at a few examples to illustrate how for loops work in PowerShell:

Example 1: Numeric Range

for ($i = 1; $i -le 5; $i++) {
Write-Host "Iteration $i"
}

This loop will print "Iteration 1" through "Iteration 5". It initializes $i to 1, increments it by 1 in each iteration, and continues as long as $i is less than or equal to 5.

Example 2: Iterating over an Array

$colors = @("Red", "Green", "Blue")
for ($i = 0; $i -lt $colors.Length; $i++) {
Write-Host "Color: $($colors[$i])"
}

In this example, the loop iterates through each element of the $colors array, printing the name of each color.

Example 3: Nested Loops

for ($i = 1; $i -le 3; $i++) {
for ($j = 1; $j -le 3; $j++) {
Write-Host "Outer: $i, Inner: $j"
}
}

This demonstrates a nested loop structure, where an inner loop is inside an outer loop. The output will show combinations of the outer and inner loop variables.

These are basic examples, and you can customize the for loop according to your specific needs in your PowerShell scripts.

Foreach Loop

The foreach loop is another way to iterate through a collection in PowerShell.

Syntax

foreach ($item in $collection) {
# Code to execute for each item in $collection
$item # $item represents the current item in the iteration
}

In this example, $collection is the array or collection you want to iterate through. $item is a variable that represents the current item in the iteration. The code within the curly braces {} will be executed for each item in the collection.

Example 1: Getting and Displaying the Square of Numbers

$numbers = 1, 2, 3, 4, 5

# Using Foreach statement
foreach ($number in $numbers) {
$squared = $number * $number
Write-Output "Square of $number is $squared"
}

In this example, you iterate through $numbers and print the square of them.

Example 2: Getting and Displaying Employee Information

Let's consider a scenario where you have a hashtable containing information about employees, and you want to iterate through the hashtable to display each employee's name and department. Here's an example using the foreach loop statement:

The syntax is:

# Hashtable with employee information
$employeeData = @{
"John" = "HR"
"Jane" = "IT"
"Bob" = "Finance"
"Alice" = "Marketing"
}


# Using Foreach statement to iterate through the hashtable
foreach ($employeeName in $employeeData.Keys) {
$department = $employeeData[$employeeName]
Write-Output "$employeeName works in $department department"
}

In this example, $employeeData is a hashtable where employee names are keys, and department names are values. The foreach loop iterates through the keys (employee names), and for each employee, it retrieves the corresponding department and prints a message using Write-Output.

The output would be something like:

John works in HR department
Jane works in IT department
Bob works in Finance department
Alice works in Marketing department

Foreach-Object cmdlet:

The foreach-object cmdlet is another way to iterate through a collection in PowerShell.

Syntax

$collection | ForEach-Object {
# Code to execute for each item in $collection
$_ # $_ represents the current item in the iteration
}

$collection is the array or collection you want to iterate through. The script block within the curly braces {} contains the code that will be executed for each item in the collection. $_ is a special variable that represents the current item in the iteration.

Note: The difference between foreach-object cmdlet and foreach loop is that results obtained from another cmdlet can be piped through to foreach-object cmdlet which cannot be one with foreach loop.

Example 1: Getting and Displaying the Square of Numbers

$numbers = 1, 2, 3, 4, 5

# Using Foreach-Object
$numbers | ForEach-Object {
$squared = $_ * $_
Write-Output "Square of $_ is $squared"
}

In this example, you iterate through $numbers and print the square of them.

Example 2: Getting and Displaying the File Length

Let's consider a scenario where you have a list of file names, and you want to display the length of each file using the Get-Item cmdlet and a ForEach-Object loop. Here's an example:

# List of file names
$fileNames = "file1.txt", "file2.txt", "file3.txt"

# Using Foreach-Object to get and display the length of each file
$fileNames | ForEach-Object {
$fileName = $_
$fileItem = Get-Item $fileName
Write-Output "$fileName has a length of $($fileItem.Length) bytes"
}

In this example, $fileNames is an array containing the names of three files. The ForEach-Object loop is used to iterate through each file name. Inside the loop, Get-Item cmdlet is used to get information about each file, and then the file length is displayed using Write-Output.

The output would be something like:

file1.txt has a length of 1234 bytes
file2.txt has a length of 5678 bytes
file3.txt has a length of 9012 bytes

Both examples demonstrate how you can use ForEach-Object to process items in a pipeline, performing actions on each item as it passes through the pipeline.

Home

Active Directory

Hyper-V

PowerShell

Free Tools

Contact

Trending News

How to enable Hyper-V in Windows? Coming Soon...

How to configure a Virtual Machine? Coming Soon...

Using PowerShell to manage a Virtual Machine Coming Soon...

How to install Active Directory on Windows Server 2016? Coming Soon...

How to create Active Directory Users? Coming Soon....

How to reset Active Directory User Passwords? Coming Soon...

How to unlock Active Directory User Accounts? Coming Soon...

Popular Resources

Popular resource 1 coming soon....coming soon

Popular resource 1 coming soon....coming soon

Popular resource 1 coming soon....coming soon

Popular resource 1 coming soon....coming soon

Table of Contents

Table of Contents

  • PowerShell For Loop
    • Syntax
    • Example 1: Numeric Range
    • Example 2: Iterating over an Array
    • Example 3: Nested Loops
  • PowerShell Foreach Loop
    • Syntax
    • Example 1: Getting and Displaying the Square of Numbers
    • Example 2: Getting and Displaying Employee Information
  • PowerShell Foreach-Object Cmdlet
    • Syntax
    • Example 1: Getting and Displaying the Square of Numbers
    • Example 2: Getting and Displaying the File Length

Connect with us!

Company
  • About admincentric
  • Advertise with us
  • Contact
Pages
  • Webinars
  • Deals Store
  • Privacy Policy
Deals
  • Hacking
  • Development
  • Android
RSS Feeds Contact Us

© admincentric, 2023. All Rights Reserved.