0

I am trying to write a script to automate VDI deployment and I have everything working except for setting the MAC addresses correctly. I am not new to writing scripts but I will say this is the most complicated yet.

I am trying to create an array with the MAC addresses and then run a foreach. But I am not sure how to make it use each object in the array when the foreach loops.

Please see a piece of the script below:

$array = @('00155d9df9b8','00155d9df921')

$i = 1

$vminstances = Read-Host -Prompt 'How many VMs?'

for ($i=1; $i -le $vminstances; $i++)

The foreach would run through names of VMs and rename accordingly. But I can't simply use a MAC address with increments of 1 each loop, as they are using different characters, not just numbers.

How can I include each object stored in the array in each loop?

Perhaps it was never designed to work like this and maybe I need to rethink this. Please could somebody advise?

I would greatly appreciate assistance.

deduper
  • 1,944
  • 9
  • 22
  • 1
    I'm not clear on your question. You are getting input for a number of VMs to create. What if the user enters a number that's greater than the number of MAC addresses in your array? – Bill_Stewart Aug 05 '20 at 21:52
  • Please [format your code and sample input/output properly](http://meta.stackexchange.com/a/22189/248777). – mklement0 Aug 05 '20 at 22:23

1 Answers1

0

Powershell makes arrays really easy to work with and you don't need to do that style of a for loop. Simply use your array in a foreach loop and then you have a variable to work with that works more like a cursor than having to read from the array using indexes...

$array = @('00155d9df9b8','00155d9df921')
foreach($mac in $array)
{
  Write-Output $mac
}
Eric J. Price
  • 2,740
  • 1
  • 15
  • 21
  • 1
    I suggest avoiding `@(...)` for array literals; e.g., instead of `@('a', 'b')`, use just `'a', 'b'`. Not only is `@(...)` unnecessary, it is inefficient in PowerShell versions up to 5.0, but - more importantly - it invites conceptual confusion by falsely suggesting that it _constructs_ arrays. For more information, see the bottom section of [this answer](https://stackoverflow.com/a/45091504/45375). – mklement0 Aug 05 '20 at 22:29
  • Note that while `Write-Output` is the right tool for outputting data, you typically don't need to use it explicitly, because PowerShell _implicitly_ outputs (to the success data stream) any expression or command that isn't captured or redirected; e.g., just `$foo` _by itself_ has the same effect as `Write-Output $foo`. While there is no harm in using `Write-Output`, consider showcasing PowerShell's implicit output feature instead (possibly with an explanatory comment), so as to promote PowerShell-idiomatic solutions. – mklement0 Aug 05 '20 at 22:33