[英]IF Statement to Verify VLAN Exists in PowerCLI Script
I am writing a PowerCLI script to automate the creation of VMs based on the data within a CSV file and I would like to know how to format an IF statement to check if the VLANs specified already exist to avoid cluttering up the screen with errors.我正在编写一个 PowerCLI 脚本,以根据 CSV 文件中的数据自动创建 VM,我想知道如何格式化 IF 语句以检查指定的 VLAN 是否已经存在,以避免因错误而使屏幕混乱。
The section of the script dealing with the VLAN creation in its current format:脚本中处理以当前格式创建 VLAN 的部分:
New-VM -Name $_.Name -VMHost ($esx | Get-Random) -NumCPU $_.NumCPU -Location $Folder
$list = Get-Cluster $_.Cluster | Get-VMHost
foreach ($esxhost in $list)
{ Get-VirtualSwitch -Name $switch -VMHost $esxhost |
New-VirtualPortgroup -Name "VLAN $($_.VLAN)" -VLANID $($_.VLAN)
}
Write-Host "Wait - propagating VLAN $($_.VLAN) to all hosts" -foreground yellow
Start-Sleep 10
I would like to determine a way to have the script do something like:我想确定一种让脚本执行以下操作的方法:
IF $_.VLAN exists
Write-host "$_.VLAN already present, proceeding to next step"
ELSE DO{ Get-VirtualSwitch -Name $switch -VMHost $esxhost |
New-VirtualPortgroup -Name "VLAN $($_.VLAN)" -VLANID $($_.VLAN)
}
I don't have much experience in writing these so I was hoping for some assistance on how to我在写这些方面没有太多经验,所以我希望得到一些关于如何编写的帮助
Check whether the VLAN already exists in vSphere on the switch在交换机上的vSphere中检查VLAN是否已经存在
How to format the IF/ELSE statement properly to avoid cluttering up the PowerCLI window with errors when the script is run如何正确设置 IF/ELSE 语句的格式以避免在运行脚本时出现错误的 PowerCLI 窗口
Thank you for any assistance you may provide感谢您提供的任何帮助
EDIT to work for vlan rather than vswitch编辑以适用于 vlan 而不是 vswitch
You could use get-virtualportgroup for this and check if the names returned contain your vlanid.您可以为此使用 get-virtualportgroup 并检查返回的名称是否包含您的 vlanid。 This won't work for distributed switches as that's a different set of cmdlets.
这不适用于分布式交换机,因为这是一组不同的 cmdlet。
$host = 'YourHost'
$vlanid = 'YourVlanId'
if ((Get-VirtualPortGroup -host $host).VLanId -contains $vlanid )
{
Write-Output 'vlan present'
}
else
{
Write-Output 'vlan missing'
#your code to create vlan here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.