Variable range operator in PowerShell
powershell-2.0, powershell-3.0
Solution
1..9 | % { $computers += "servername$_`n" }
And the variable $computers will contain:
servername1
servername2
servername3
[...]
Try running only the `1..9` part on your command line and it'll be easier to see what's gonig on. You could also read up on arrays in PowerShell with `Get-Help about_Arrays` - look for the part about "range operator" near the beginning.
The following line of code does the same thing (and seems cleaner to me) and might be easier to understand as well.
$computers = 1..9 | foreach { "servername$_" }
Or simply `1..9 | foreach { "servername$_" }` to see it on screen without saving it in a variable.
Problem
I am trying to use a range operator to input a series of numbers for use in a PowerShell script. Here is my code: ``` $computers = servername + [1-9] ``` I would like the $computers variable to iterate the 1-9 i.e., servername1, servername 2, etc. etc. Any ideas?