4 Replies Latest reply on Aug 20, 2019 8:48 AM by eaphilipp

    VM search by IP

    eaphilipp Enthusiast

      Hi Everyone. I am trying to write a little script to search for a VM via IP. It seems to work accept the part where if it doesn't find anything it reports back No VMs Found. Here is my code.

       

      What am I missing:

      $ip = $null

      $ip = read-host "Please Enter IP Address of VM you want to search for "

      If ($ip -ne $null)

      {

      Get-VM | where-object{$_.Guest.IPAddress -eq $ip } | select name

      }

      else

      {

      write-host "No VMs Found"

      }

       

      Thanks as always for the help.

        • 1. Re: VM search by IP
          LucD Guru
          Community WarriorsvExpertUser Moderators

          Try like this

           

          $ip = Read-Host "Please Enter IP Address of VM you want to search for "

          If ($ip -ne '')

          {

             $found = Get-VM | where-object { $_.Guest.IPAddress -eq $ip } | select name

             if (-not $found)

             {

             Write-Host "No VM with IP $ip found"

             }

          }

          else

          {

             Write-Host "No IP provided"

          }

          • 2. Re: VM search by IP
            eaphilipp Enthusiast

            Ok, this worked for the not found part. Yay! But when it found the VM with that IP it didn't return the VM name on the screen. I am assuming it appears to be stored in the $found variable. Whats the best way to extract that information from $found. Ideally I want to put this in a menu system and have the option to repeat it...

             

            But for now just getting this to work would be sweet!

            • 3. Re: VM search by IP
              LucD Guru
              Community WarriorsvExpertUser Moderators

              One way to do that would be

               

              $ip = Read-Host "Please Enter IP Address of VM you want to search for "

              If ($ip -ne '')

              {

                 $found = Get-VM | where-object { $_.Guest.IPAddress -eq $ip }

                 if (-not $found)

                 {

                 Write-Host "No VM with IP $ip found"

                 }

                 else

                 {

                 Write-Host "Found VM $($found.Name)"

                 }

              }

              else

              {

                 Write-Host "No IP provided"

              }

              1 person found this helpful
              • 4. Re: VM search by IP
                eaphilipp Enthusiast

                Awesome. Yes that is a good solution. Thanks as always for the help.