title: Building a working foreach loop on Get-VM
body: <p>I'm trying to build a loop that will take the Get-VM cmdlet, put it into an array, and let me run a foreach statement on each VM.  When I have that array built, the loop should go to each VM, build the designated amount of VHDs, initialize them, format them, and attach them to the VM.  </p>
  
  <p>The logic in the script works.  It will build a disk and attach it to the VM.  Where I'm failing is that the script will error out saying that the machine it is trying to build is already created (I suspect a scope error in my $val variable).  It will also stop and not move to the next object.  </p>
  
  <p>I suspect I have scope errors, and also that ForEach-Object might be a better way to go on this script.  However at this point I'm lost and need a little help. </p>
  
  <p>As always, thank you and happy coding!</p>
  
  <pre><code>Write-Host "This script is set up for quickly creating and initilizing VHDs"
  $Path = Read-Host "Please enter the path you want to create the drives to. Use the format in this example &lt;E:\VHDS\&gt;"
  $fileName = Read-Host "The Drive will be &lt;target&gt;-&lt;number&gt;.vhdx.  Please Name the target "
  $vhdSize = 1GB
  $vmAmount = 1
  
  $GetVM = Get-VM
  
  Foreach ($vm in $GetVM)
  {
      $n = $vm.Name.ToString()
      $val = 0
      For($internalCounter = 0; $internalCounter -le $vmAmount; $internalCounter++)
          {
              $vhdPath = (Join-path $Path  ($fileName + '-' + $val + '.vhdx'))
              New-VHD -Path $vhdPath -SizeBytes $vhdSize -Fixed 
              Mount-VHD -Path $vhdPath
              $disk = get-vhd -path $vhdPath
              Initialize-Disk $disk.DiskNumber
              $partition = New-Partition -AssignDriveLetter -UseMaximumSize -DiskNumber $disk.DiskNumber
              $volume = Format-Volume -FileSystem NTFS -Confirm:$false -Force -Partition $partition
              Dismount-VHD -Path $vhdPath
              Add-VMHardDiskDrive -VMName $n -Path $vhdPath
          }
       $val++
  }
  </code></pre>