Stupid question I suppose

$Vms = Get-VM

ForEach ($Vm in $Vms) {

I never have understood how the singular variable ‘$VM’ gets its value?

The variable $vms will contain a collection of virtual machines.

The next line is saying foreach virtual machine in the collection of machines execute the bit of code within the brackets.

You now want to reference $vm because we are referencing a single machine within that collection. It wouldnt make sense to say $vms because thats the whole collection.

Hope that made some sense?

It’s what the ForEach construct does for a living.

Variable 2 has one or more objects; one at a time is taken and put into variable 1. That’s literally what ForEach is doing, and that’s how it happens. Nearly all programming languages have an equivalent construct.

So… to look at it a different way…
The line could read
`ForEach ($XYZ in $Vms)`
and work the same yes?

Yes, absolutely. PowerShell doesn’t assign any semantic meaning to variable names. You’d use $VM and $VMs because it helps you keep track, not because PowerShell cares. In fact, I use almost that exact explanation in Learn PowerShell in a Month of Lunches, because thinking the plural vs. singular variable names are important is a huge hangup for a lot of beginners… in any programming language, not just PowerShell.

I thank all for the response. The problem with anything is doing and doing it more. I want to master powercli. I am learning quick that to do so requires mastering Powershell.

This is the first time I have been excited about learning Microsoft technology! Powershell is really the greatest thing that Microsoft has developed since WINXP. I really want to use powershell as a means to have a deeper understanding of the underlying windows technology.