Powershell:如何逐步扩大循环中的变量?

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

我是 scripting/PowerShell/PowerCLI 新手。我的任务是弄清楚如何最好地完成扩展我们现有的一些脚本。

我们的脚本从我们的最终用户那里获取 YAML 输入,并根据他们的规范构建 VMware ESXi 集群。我们正在尝试扩展脚本,以便我们可以根据用户在 YAML 中指定的集群类型应用不同的配置。我们希望最终用户能够扩展它以根据需要创建尽可能多的集群。同时根据他们输入的集群类型应用不同的配置。我们还希望将来能够轻松扩展 Cluster"X"Type out 以用于我们最终定义的其他类型。

YAML 输入示例:

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

我知道我可以用一种相当不干净的方式来做到这一点,即硬编码很长的 if 和语句。类似于:

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>}

我知道必须有更好的方法来解决这个问题。如果我没记错的话,vSphere 6.5 每个 vCenter 最多可以有 64 个集群,绝对不想每次我们需要检查最终用户分配给特定集群名称的集群类型时都硬编码 64 if else 语句。我一直在寻找一个干净的解决方案,但我的经验不足让我很难自己找到答案。

我还认为可以为集群名称使用变量数组,然后提示执行我们的 PowerShell 脚本的用户为他们输入到数组中的每个集群名称输入集群类型。我仍然认为可能有比这更好的方法?可能是 运行 在增量方法中对每个 ClusterX 和 ClusterXType 变量进行循环的方法?

您可以使用 New-Variable 命令创建一个使用另一个变量作为名称的变量

$iteration = 1
New-Variable -Name Cluster$iteration

这将创建一个名为 $Cluster1

的变量
Get-Variable C*

Name          Value
----          ----
Cluster1

你是在说这样的话吗? 这是假设用户一次只能输入一种集群类型。

# Specify the number of cluster nodes to create
$ClusterCount = Read-Host -Prompt 'Enter the number of guests to create'

# Enter a cluster type to create
$ClusterType = Read-Host -Prompt 'Enter the type - Basic, DR, Replicate'

1..$ClusterCount | 
ForEach{
    "Working cluster type $ClusterType on new node name Cluster$PSITEM"
    <#
    If ($ClusterType -eq 'DR') {"Code to execute on Cluster$PSItem"}
    ElseIf ($ClusterType -eq 'Replicate') {"Code to execute on Cluster$PSItem"}
    Else {<Code to execute on $Cluster1>}
    #>
}

# Results

Enter the number of guests to create: 3
Enter the type - Basic, DR, Replicate: Basic
Working cluster type Basic on new node name Cluster1
Working cluster type Basic on new node name Cluster2
Working cluster type Basic on new node name Cluster3

我们最终在 YAML 中创建了一个对象数组。然后将 YAML 导入我们的脚本并通过 Clusters.Name / Clusters.Type 调用每个脚本。感谢大家的帮助,让我学习了完成此任务或类似任务的各种方法。

集群: - 姓名:XXXXX 类型:XXXXX