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

问题描述 投票:0回答:3

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

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

YAML输入示例:

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

我知道我可以用一种非常不干净的方式来做这件事。就像是:

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变量运行循环的方法?

powershell yaml powercli
3个回答
1
投票

你在说这样的话吗?这假设用户一次只允许输入一个群集类型。

# 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

0
投票

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

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

这将创建一个名为$Cluster1的变量

Get-Variable C*

Name          Value
----          ----
Cluster1

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.