Automation

 View Only
  • 1.  params check if $null

    Posted Sep 08, 2022 03:46 PM

    I got a param script and need to get vmhost info

     

    params($vc,$dc,$cluster,$vmhost)

    if ($dc -or $cluster -eq $null) {

    get-vmhost $vmhost | select Name, etc.....

    }

    else if ($cluster -and $vmhost -eq $null}

    get-datacenter $dc | get-vmhost | select Name, etc....

     

    else if ($vmhost -eq $null}

    get-datacenter | get-cluster | get-vmhost | select Name etc....

     

    Is this correct?



  • 2.  RE: params check if $null

    Posted Sep 09, 2022 05:30 AM

    If I understand what you are trying to do I would opt for parametersets.
    Something like this

      [CmdletBinding(DefaultParameterSetName = 'Default')]
      param(
      [Parameter(ParameterSetName = 'Datacenter',
        HelpMessage = 'Enter a Datacenter name')]
      [string]$DC,
      [Parameter(ParameterSetName = 'Cluster',
        HelpMessage = 'Enter a Cluster name')]
      [string]$Cluster,
      [Parameter(ParameterSetName = 'VMHost',
        HelpMessage = 'Enter a VMHost name')]
        [string]$VMHost,
      [String]$vc
      )
    
      if ($PSCmdlet.ParameterSetName -eq 'Datacenter') {
        Get-Datacenter $dc | Get-VMHost | Select-Object Name
      }
      elseif ($PSCmdlet.ParameterSetName -eq 'Cluster') {
        Get-Cluster -Name $Cluster | Get-VMHost | Select-Object Name
      }
      elseif ($PSCmdlet.ParameterSetName -eq 'VMHost') {
        Get-VMHost $vmhost | Select-Object Name
      }
      else{
        Get-Datacenter | Get-Cluster | Get-VMHost | Select-Object Name
      }