EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Loop through Array
Secondary Sidebar
PowerShell Tutorial
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

PowerShell Loop through Array

PowerShell-Loop-through-Array

Definition of PowerShell Array

PowerShell array is a collection of the single datatype or the multiple different datatypes values and looping through the array means scanning each value one by one using different available loops in PowerShell like While, For, Foreach, Do-While, etc and performing the operation on each item if required and this loop operations are generally with the index one in the background.

Syntax:

  • Foreach loop Syntax with an array.

Foreach ($item in $collections) { $item}

  • For loop syntax with an array.

for($i=0; $i -lt $Collection.Length; $i++) { $collection[$i] }

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,650 ratings)
  • While loop syntax with an array:

$i=0
while($i -lt $Collection.Length) { $Collection[$i]; $i++ }

  • Do-While loop syntax with an array:

$i=0
while($i -lt $Collection.Length) { $Collection[$i]; $i++}

  • Foreach-Object -Parallel loop with an array Syntax (Works with PowerShell 7).

$Collection | ForEach-Object -Parallel { $_ }

How does the loop through PowerShell Array works?

Suppose we have this sample array.

$array = 10, "Animals" , "Clouds" , 5.4
$array

Output:

powershell 1

We know that an array is nothing but simply the collection of objects. Array works on the concept of indexing. To access the particular array value, we need to index that item. For example,

$array[2] $array[3]

Output:

array

Loops like While, For, Do-While uses the same concept. They browse through each index of the array. Below is the example of For loop.

$i = 0
for($i=0 ; $i -lt $array.Length; $i++) { $array[$i] }

Output:

powershell 2

In this example, the loop increments the value of an index until the value becomes the length of the array and terminates and in this way, it prints the entire array. If you need to print only a few members then provide length up to it. For example,

for($i=0 ; $i -lt 3; $i++) { $array[$i] }

Output:

for loop

The same looping concept works with the While and Do-While loop.

$i = 0
while( $i -lt $array.Length ) { $array[$i]; $i++ }

With a Do-While loop.

$i = 0
do{ $array[$i]; $i++ } While( $i -lt $array.Length )

The foreach loop works a little differently. It doesn’t work on the indexing concept. Let’s check the below example.

foreach( $arr in $array ) { $arr }

Here, the Foreach loop rolls through each item until the array becomes Null. This makes the Foreach loop much easier and flexible because we don’t want to specify any index or any condition and the $arr variable contains every single item.

When we are dealing with the large chain of array values, the Foreach loop parallel loop makes the execution quicker.

The Foreach-Object -Parallel command only supported in PowerShell version 7 or above. This command works as below with an array.

$array | ForEach-Object -Parallel { $_ }

It takes the array value from the pipeline and $_ stores each value.

Examples

Example #1: Services Array example with Loop.

When we use variable to store Get-Service output, that variable is now an array of multiple services.

$services = Get-Service
$services.GetType()

Output:

example 4

That means we can use the different loops with the $services variable.

This is how we can use Foreach loop with the above array.

foreach( $ser in $services ) { Write-Output “Service: $($ser.name), Status: $($ser.status)” }

The above command loops through an $services array and $ser variable stores each instance of the service one by one.

Output:

output 2

We can also use the below command directly,

foreach( $ser in (Get-Service) ) { Write-Output "Service: $($ser.name), Status: $($ser.status)" }

In the above example, Get-Service is directly passing and it has become an array input. When we use the Array with loop we can minimize the efforts by performing the operation in the same foreach or other loops.

For example,

Instead of writing multiple lines as shown below,

$service = Get-Service | where { $_.StartType -eq 'Automatic' }
foreach( $ser in $service) { Write-Output "Service: $($ser.name), Status: $($ser.status)" }

We can use the below command directly in Foreach loop.

foreach( $ser in (Get-Service | where{$_.StartType -eq 'Automatic'}))
{
Write-Output "Service: $($ser.name), Status: $($ser.status)"
}

Example #2: Passing array as Pipeline to the Foreach-Object loop.

Another method, we can use is passing an array through the pipeline. For example,

Get-Service | ForEach-Object { $_ }

Here, each line is processed one by one, and the variable $_ stores the current line each time the loop is processed. We can operate on each item as shown below.

Get-Service | ForEach-Object {
$_ | where {$_.StartType -eq 'Disabled'} | Select Name
}

Output:

name

You can also use the -Parallel parameter with the PS7 version.

Get-Service | ForEach-Object -Parallel {
$_ | where {$_.StartType -eq 'Disabled'} | Select Name
}

Example #3: Loop through a File.

When we work with the File content, we store them using Get-Content and that file content storage variable becomes the string array and we can process them individually. For example,

We have the below servers.txt file and we need to test the connectivity of the server so we can use the below code.

Servers.txt file

server text

foreach( $Server in (Get-Content .\Servers.txt)) {
if( Test-Connection $Server -Count 1 -Quiet -EA Ignore){
Write-Output "$server connection successful"
}
else{
Write-Output "$server connection failed"
}
}

Example #4: Loop through the CSV file.

Suppose we have a EmpData.csv file and we need to pass it to the loop and once we get the content from it, it becomes an array and we can process each content with loop.

v

Import-CSV C:\temp\empdata.csv| where {$_.City -eq 'New York'} | ForEach-Object { $_ }

Output:

example 6

Conclusion

PowerShell Array and PowerShell loop individually and with their combinations scripter use in their daily activity because almost everything is in the form of the objects and even files like TXT, JSON, CSV, etc can be looped through an array and makes it easier to process the multiple data without interventing users.

Recommended Articles

This is a guide to PowerShell Loop through Array. Here we discuss the Introduction, syntax, How does the loop through PowerShell Array works? examples with code implementation. You may also have a look at the following articles to learn more –

  1. PowerShell Match
  2. PowerShell change directory
  3. PowerShell uninstall module
  4. PowerShell Wait
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more