Loop Array Elements in Windows PowerShell Scripts

Q

How to loop through all elements in an array in Windows PowerShell scripts?

✍: FYIcenter.com

A

An array has a special property called "Length", which holds the length of the array or the number of members in the array.

The "Length" property can help you to loop through all members using a simple "For {...}" loop as shown below:

$w = @("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
"There are "+$w.Length+" days in a week:"
For ($i=0; $i -lt $w.Length; $i++) {
   "   "+$w[$i]
}

You can also the "Foreach (...) {...}" loop to loop through each member in array as show in the following example:

$w = @("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
"Week days:"
Foreach ($d in $w) {
   "   "+$d
}

 

Hashtable in Windows PowerShell Scripts

Array in Windows PowerShell Scripts

Introduction of Windows PowerShell Script

⇑⇑ Windows PowerShell Tutorials

2016-10-29, 1834🔥, 0💬