【问题标题】:IF Statement to Verify VLAN Exists in PowerCLI Script用于验证 PowerCLI 脚本中是否存在 VLAN 的 IF 语句
【发布时间】:2016-12-07 13:40:53
【问题描述】:

我正在编写一个 PowerCLI 脚本,以根据 CSV 文件中的数据自动创建 VM,我想知道如何格式化 IF 语句以检查指定的 VLAN 是否已存在以避免屏幕混乱错误。

以当前格式处理 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 

我想确定一种让脚本执行以下操作的方法:

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

我在编写这些方面没有太多经验,所以我希望在如何编写这些方面得到一些帮助

  1. 检查交换机上vSphere中是否已经存在VLAN

  2. 如何正确格式化 IF/ELSE 语句以避免在运行脚本时因错误而使 PowerCLI 窗口混乱

感谢您提供的任何帮助

【问题讨论】:

    标签: powershell automation vmware powercli


    【解决方案1】:

    编辑为 vlan 而不是 vswitch 工作

    您可以为此使用 get-virtualportgroup 并检查返回的名称是否包含您的 vlanid。这不适用于分布式交换机,因为那是一组不同的 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-16
      • 2012-10-02
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多