AlanRaczek
Contributor
Contributor

Search vCenter for a particular host

This is probably an easy answer but I just can't wrap my head around this at the moment. I want to search vCenter for the existence of a specific host. I have this code below. I know the issue that it won't necessarily give me correct output because it iterates through the entire collection and thus even if a host exists it will still give me the message that the host doesn't exist. I am not creative, thus I don't know how I should break out of this loop other than calling a function.

$vchost = "192.168.172.128"
#$vchost = "192.168.172.138"

get-vilogin
function host-exist {
  #Does host exist on vCenter?
  $script:ALLVMhost =  get-vmhost | Select Name
  #Get the Name property from the enumerated full host array
  foreach ($ALLVMhosts in $ALLVMhost.name)
  {
      if ($ALLVMhosts -eq $vchost){
        $HOSTexist = "true"
        $hostexist
        write-host "Host exists" -ForegroundColor Yellow
        break
      } else {
        #host does not exist on vCenter
        $HOSTexist = "false"
        $HOSTexist
        Write-host "*** Host entered does not exist on this vCenter Server! ***" -ForegroundColor Red
        #get-VcHostVMs
      }
  }
}
host-exist

 I am obviously missing something. Should I use do...until or while? Or a pipeline?

..ar

Labels (1)
  • t

0 Kudos
4 Replies
LucD
Leadership
Leadership

What about just a Get-VMHost with the name?

$vchost = "192.168.172.128"

function host-exist {
    if (Get-VMHost -Name $vchost -ErrorAction SilentlyContinue) {
        Write-Host "Host exists" -ForegroundColor Yellow
    } else {
        Write-Host "*** Host entered does not exist on this vCenter Server! ***" -ForegroundColor Red
    }
}

host-exist


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
AlanRaczek
Contributor
Contributor

 

Okay I'm confused. If -ErrorAction SilentlyContinue executes doesn't it mean that the host was not there? That seems to tell me anyway that yes there was an error so continue and print "Host exists".

0 Kudos
LucD
Leadership
Leadership

No, that means no error will be shown.
If a VMHost object is returned, the IF will pass.
If no object is returned, the ELSE will run


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
AlanRaczek
Contributor
Contributor

Of course, okay got it now! Stressful week on a number of fronts 😫

0 Kudos