Stupid question I suppose

This topic contains 5 replies, has 4 voices, and was last updated by  konfigurationking 3 years, 1 month ago.

  • Author
  • #22487


    $Vms = Get-VM

    ForEach ($Vm in $Vms) {

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

  • #22488

    Adnan Rashid

    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?

  • #22489

    Don Jones

    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.

  • #22490

    Greg Altman

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

  • #22491

    Don Jones

    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.

  • #22575


    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.

You must be logged in to reply to this topic.