r/PowerShell • u/InfoZk37 • May 14 '26
Solved Would someone mind helping me understand how "foreach ($computer in $computers)" works?
I know foreach iterates through an array, of sorts. I'm just wondering, since I didn't define $computer, how does it know to single out each individual item from my $computers array? Is it a predefined variable, or could I just place anything there? Like "foreach ($x in $computers)".
$computers = get-adcomputer ##just an example that the latter variable was defined by me, but $computer was not.
I think I convinced myself that I'm right in thinking I could place anything there, like $x or $flapjacks or whatever, but some confirmation would be nice. And if I'm wrong then being corrected is even more welcome. Thank you.
20
u/Panchorc May 14 '26
The official docs covers that very well: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_foreach?view=powershell-7.6
12
u/mixduptransistor May 14 '26
Yes, in the statement ($x in $y) the $x can be anything you want it to be. The $y has to be an actual array, of course, but what it is doing is for every run of the loop it's putting a single value of $y into $x. People name it similarly to the array to make the code readable but there's no requirement to do that
10
u/nitroed02 May 14 '26
It's recommended to avoid using ($computer in $computers) and instead use something like ($computer in $computerList). This greatly reduces the likelihood of accidentally referencing the $computers aray inside the loop and do unexpected things.
3
u/coaster_coder May 14 '26
The variable before
inis a reference to the item from the array currently being processed. The foreach loop will execute one time for every object in the array. You can absolutely define this variable as anything you want. Typical patterns include a a single letter variable where the letter is the first letter of the variable that contains the array. In your example that would be$cas the current item being processed from the$computers.The important thing to remember is that the thing to left of
inis what is currently being evaluated and that the thing on the right ofinis the thing the the left ofincame from.3
u/PinchesTheCrab May 14 '26 edited May 14 '26
Personally I'd rather see $tooth in $flapjacks because in addition to being funny, a simple typo can cause you to perform an action on the entire array.
Not all cmdlets accept an array, but some do, and you can perform destructive actions if you accidentally remove $files instead of $file.
63
u/TheEdonReddit May 14 '26
You are correct. You are defining it there and can name it just about whatever you want.
3
u/branhama May 14 '26
Variables in PowerShell are usually configurable. There are exceptions such as environment variables. For instance "$env:COMPUTERNAME", this variable is built into PowerShell as a system variable and is static. However based on your example the sky is the limit.
$myComps = ('comp1', 'comp2', 'comp3')
foreach ($singleComp in $myComps) { Write-Host $singleComp }
For the most part you always want to keep your variables self documented. For instance I would not use $x unless you are at the CLI. In scripts, if you want to make scripts others will use, always define your variable properly. $Computers or $Comps... If I look at code and all your variables are random, I will look right past your code and not use it. Makes troubleshooting problematic.
3
u/Fallingdamage May 14 '26
foreach ($object in $array)
All you're doing is assigning a variable name to individual objects from the array. The machine doesn't care what you call it.
3
u/_litz May 14 '26
You did define it. ForEach handles that for you.
As for its type, it derives that when each element of the array is, in sequence, assigned to it.
2
u/chaosphere_mk May 14 '26
Yep, you could definitely do foreach($x in $computers). $x in this instance is you telling powershell how you want to refer to the current item within the foreach loop.
2
u/ca_269 May 14 '26
You’re right… you could name it anything you want. The variable is created for the loop, and on each iteration, an item from the array is assigned to that variable. As you said, you could use $x, but in my experience, it’s better to use a meaningful name, like:
foreach ($student in $classList) { $fn = $student.FirstName }
2
u/digital-plumber May 14 '26
This might be a deeper answer than you're looking for, if so, sorry, but it should explain how foreach works internally, to the best of my knowlege.
firstly, the actual variable is defined as you reference it, as others have said.
PowerShell objects are .net framework objects, foreach in powershell is leveraging how arrays and collections work in .net
There's a thing called an interface, which is like a contract in that if something agrees to implement an interface, it must define the members (generally properties and methods) of that interface.
There are two key interfaces related to enumeration in .net
IEnumerator<T> and IEnumerable<T>, where T is a placeholder for the type of object being enumerated.
IEnumerable defines GetEnumerator, which just signals that a type can be enumerated, with the returned enumerator
IEnumerator defines the properties and methods for actually enumerating, in particular
T Current - gets the current objects
bool MoveNext() - Moves the enumerator to the next object in the collection (accessble through Current)
when you do a foreach in powershell, or .net, it's actually enumerating the collection using it's enumerator, which it gets by calling GetEnumerator
if you did this
foreach($x in $collection)
{
//Your code here.
}
It might look something like this in PowerShell if you did it manually
$e = $collection.GetEnumerator()
while($e.MoveNext()}
{
$x = $e.Current
//Your code here
}
Hopefully that helpful to someone.
2
u/bdanmo May 14 '26
if you wanted, you could do foreach ($shartsicle in $computers) to keep your code fun and interesting for yourself and others
2
u/OK_it_guy May 14 '26
I've never really thought about "how" it works, just know that it does; however, I salute you for not being afraid to ask something that we take for granted.
2
u/inperbio May 14 '26
yep you nailed it, $computer is just a variable you're declaring on the fly right there in the loop syntax. powershell creates it automatically each iteration and assigns the current item to it. you could write foreach ($flapjacks in $computers) and it works exactly the same way, $flapjacks just holds each computer object as it cycles through.
2
u/HelloFelloTraveler May 16 '26 edited May 16 '26
I always think of it as using a spreadsheet. Where $computers is the spreadsheet and $computer becomes a variable of each row as the for each loop goes through it.
So if you needed to use $computers.deviceName to get a list of all device names in it. You could also use $computer.deviceName to get the specific deviceName from each row as the loop goes through.
Each header(key) points to a value in that column.
If you’re using a list, the. You no longer use keys with your $computer variable, so then you’re just doing a loop through each comma separated value which is what you would get in your $computer variable.
You can make the variable name whatever you’d like it to be, it’s always grabbing the row/value, so you could make it
foreach ($bob in $computers)and get the same results..1
u/ShoeBillStorkeAZ May 14 '26
For every a in your list of computers do this.
1
u/true_zero_ May 14 '26
Your next task is to learn the -Parallel flag. Your CPU may get hammered while your loops run if you use -Throttle 10 , try a lower number to see how it works.
It’s in Powershell 7+ (pwsh.exe) which I highly recommend for its PSReadline predictonViewStyle alone which i have new hires configure to flatten the powershell learning curve.
Be careful with -Parallel and trying to update an outside variable in each loop with the loop’s results. -Parallel creates seperate runspaces each with their own pipeline, copy of variables, and memory space so you can’t just update an outer variable from inside the loop like you can when not using -Parallel. You have to output objects from the parallel block into a variable.
1
u/techster79 May 14 '26
Each item in the $y or $itemvariables is treated as $x or $itemvariable or whatever you name it. When dealing with computers it's intuitive to do foreach ($computer in $computers) {<cmdlet> -ComputerName $computer}
foreach ($x in $y)
{loops through items in $y and each loop is $x}
foreach ($itemvariable in $itemvariables){
Do something with $itemvariable
}
1
u/ddBuddha May 14 '26
It’s because the code you’re writing is telling it what to do “for each” one of those elements
1
u/teamhog May 14 '26
Line up your family.
It’s a special day and your mother is handing out $100 bills.
She takes a bill hands it to each of the people. Then we she gets done she goes and get birthday cake.
She just executed a for/each on the family array.
1
u/Ecrofirt May 15 '26 edited May 15 '26
I haven't read the comments here, but I'll describe it similarly to how I'd describe it to students in a class.
In your case, $computers is an array of objects. Rather than thinking like a programmer, think of it like the tracks on an album, say Paranoid by Black Sabbath.
I don't know about you, but I like to listen to albums from start to finish. To do that, I play the album. When it starts up, I'm listening to track #1, War Pigs. Each track has a different name, length, etc. To make things easy, I'm going to refer to whichever track I'm currently listening to as $computer.
When the album is playing, only one track is playing at a time. So if I asked you the name of the current track with a question like "What is $computer.Name?" you'd be able to tell me "War Pigs".
Now War Pigs is over and it's time for track 2, Paranoid. Our current track, $computer, is now Paranoid. If I asked you again "What is $computer.Name?" You'd be able to tell me "Paranoid". And so on and so forth as we worked our way through the album until we finally finished the last song, Fairies Wear Boots. At that point, the album is done and you've listened to each track.
Those names seem a bit silly for music though, don't they? Let's make it look a bit more like code.
$album = Paranoid by Black Sabbath
foreach ($track in $album)
{
Write-Host "Track name:" -NoNewLine
Write-Host $track.Name
}
1
u/TofuBug40 May 14 '26
It works the same way as literally every other functional and object oriented language ever.
foreach ($Computer in $Computers) {}
Is tokenized to
[Keyword (foreach)] ( [indexed Item ($Computer)] [Keyword (in)] [Collection ($Computers)] ) [scriptblock ( {} )]
The interpreter in this case first checks how a foreach loop is supposed to be structured once that passes it one at a time (but not in the same guaranteed order they are set) it shoves each item from the [Collection] into the [Indexed Item] and then executes the [scriptblock] with [Indexed Item] scoped to [scriptblock]
This is just one version of foreach in powershell there are two others.
ForEach-Object which is a Cmdlet which takes advantage of the pipeline to add other cmdlets downstream.
$SomeCollection.ForEach() $SomeCollection.ForEach{}
Which are methods off of anything Collection shaped nearly the fastest and gives you the ability to chain calls or output directly to a new Collection.
Both of these utilize the standard $_ variable which you can read as just the currently [Indexed Item] but you don't have to explicitly define it though you could say
foreach ($_ in $Computers) {}
-1
u/nodiaque May 14 '26
In PowerShell, you don't define anything. Everything get define as you go.
In a for each loop, in the background, it's like doing a
For ($x =0; $x < $array.size; $x++) { $computer = $computers[$x] (your code here) }
That's what a foreach loop does.
The object type doesn't mind in PowerShell, it is inherit from the array object. If it's unknown, it will just be an object.