Search code examples
powershellyamlpowercli

Powershell: How to incrementally scale up variables in a loop?


I'm a scripting/PowerShell/PowerCLI novice. I am tasked with figuring out how best to accomplish scaling out some of our existing scripts.

The scripts we have take YAML input from our end users and build out VMware ESXi clusters to their specification. We are trying to expand the scripts so that we can apply different configuration depending on the type of cluster the user specifies in the YAML. We want the end user to be able to expand this out to create as many clusters as needed. All the while applying different configuration based on the type of cluster they input. We also want to be able to easily expand Cluster"X"Type out in the future for other types we eventually define.

YAML input examples:

Cluster1: <Name>
Cluster1Type: <Basic, DR, or Replicate>
Cluster2: <Name>
Cluster2Type: <Basic, DR, or Replicate>

I know I could do this in a fairly unclean manner of hardcoding a very long if and statement. Something like:

If ($Cluster1Type -eq 'DR') {<Code to execute on $Cluster1>}
ElseIf ($Cluster1Type -eq 'Replicate') {<Code to execute on $Cluster1>}
Else {<Code to execute on $Cluster1>}

If ($Cluster2Type -eq 'DR') {<Code to execute on $Cluster2>}
ElseIf ($Cluster2Type -eq 'Replicate') {<Code to execute on $Cluster2>}
Else {<Code to execute on $Cluster2>}

I know there has to be a better way to go about this. vSphere 6.5 can have up to 64 clusters per vCenter if I remember right, definitely, don't want to hardcode 64 if else statements every time we need to check what cluster type the end user has assigned to a specific cluster name. I have been looking for a clean solution but my inexperience is making it challenging to find an answer on my own.

I was also thinking it may be possible to use a variable array for the cluster names and then prompt the user executing our PowerShell scripts to input the cluster type for each cluster name they input into the array. I still think there might be an even better way than this though? Possibly a method of running a loop on every ClusterX and ClusterXType variable in an incremental method?


Solution

  • We ended up instead, creating an array of objects in YAML. Then importing the YAML into our scripts and calling each by Clusters.Name / Clusters.Type. Thanks for the help everyone definitely got me learning various ways to accomplish this task or similar tasks.

    Clusters: - Name: XXXXX Type: XXXXX