Author Posts

February 10, 2015 at 1:51 pm

$Vms = Get-VM

ForEach ($Vm in $Vms) {
$Vm.GetType()
}

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

February 10, 2015 at 1:57 pm

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?

February 10, 2015 at 2:01 pm

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.

February 10, 2015 at 2:13 pm

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

February 10, 2015 at 2:19 pm

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 [i]Learn PowerShell in a Month of Lunches,[/i] 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.

February 12, 2015 at 8:41 pm

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.