Stupid question I suppose

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of konfigurationking konfigurationking 1 year, 9 months ago.

  • Author
    Posts
  • #22487
    Profile photo of konfigurationking
    konfigurationking
    Participant

    $Vms = Get-VM

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

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

  • #22488
    Profile photo of Adnan Rashid
    Adnan Rashid
    Participant

    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
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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
    Profile photo of Greg Altman
    Greg Altman
    Member

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

  • #22491
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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
    Profile photo of konfigurationking
    konfigurationking
    Participant

    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.