I understand that foreach loops through a collection, but I'm trying to understand what happens in an expression like `foreach ($computer in $computers)`. I created `$computers`, for example with `Get-ADComputer`, but I didn't define `$computer` beforehand. Is `$computer` a predefined variable, or can I choose any name, such as `$x` or `$flapjacks`? How does PowerShell assign each individual item to that variable during the loop?
3 Answers
The collection does not have to be strictly an array. `foreach` can enumerate many collection types, such as lists, queues, stacks, hash tables, and other objects that provide an enumerator. Conceptually, this means: take the next item from `$computers`, put it in `$computer`, run the loop body, then repeat until there are no items left.
Use descriptive names when writing scripts. `$x` works, but something like `$computer` or `$currentComputer` makes it much easier to understand what the code is doing. Also be careful with similar variable names: accidentally using the whole collection where you intended to use the current item can cause unexpected results, especially with commands that modify or remove things.
That’s good advice. Short names are fine for quick interactive commands, but descriptive names make mistakes much easier to spot in a script.
You’ve got it: the variable before `in` is created for the loop, and you can name it whatever you like. On each iteration, PowerShell assigns the next item from the collection to that variable. These are equivalent in behavior: `foreach ($computer in $computers) { ... }` and `foreach ($x in $computers) { ... }`. Meaningful names are usually better for readable scripts.
So `$computer` is just the name for the current item, not a special built-in variable. The collection on the right supplies the values, one at a time.

That distinction helped me too—`$computers` is the source collection, while `$computer` is the individual object currently being processed.