I’m trying to create an Excel file to populate VMware servers informations (using PowerCLI).
The problem I’m having is that I want to create an Excel file with “X” worksheets (where X should be the number of physical servers) and then rename them to each server.
What I have so far:
The problem is that in this way, the Excel file is created 15 worksheets are created and correctly renamed, but to fill the cells later I need that “Worksheet#number” variables to exist.
I was thinking about ignoring the first foreach and the code to fill the $variables and use something like:
Anytime you think you want to increment a variable name like that, it means what you probably wanted was a collection. I’m not sure exactly what your code is trying to do, but instead of $worksheet$i and New-Variable, you would instead reference something like $worksheets[$i], where $worksheets would be an array or other collection that you build up previously.
If you really do want to use New-Variable with dynamically-generated names for some reason, then later on, you’ll need to use Get-Variable in order to retrieve those values. “$worksheet$i” doesn’t work; $worksheet and $i are treated as two separate variables. However, this would work: Get-Variable -Name “Worksheet$i” -ValueOnly
There’s no advantage, in this code, to naming the $worksheet01 versus $worksheet (or to having an array of $worksheets, either; you already have that, in the form of the .Item() collection on $workbook01.Sheets). Since it’s in a loop, it doesn’t really matter.