Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerCLI - Finding Virtual Machine via VM IP

I am trying to locate specific VM's based from IP addresses in PowerCLI. I found this script online Grabbing VM ipaddress via PowerCLI

The intial question explaines the issues I was having, and the answer looks to resolve such issues, however when I run such script:

Get-View -ViewType VirtualMachine | Select @{N='IP';E={[string]::Join(',',$_.Guest.net.IPAddress)}}

All I get is the following output:

IP
--

And that's it... Am I missing input such as specifying a cluster or DC, does this work for anyone else?

like image 404
StackUser_py Avatar asked Mar 02 '15 09:03

StackUser_py


2 Answers

Get-View

As KERR pointed out, the code in bxm's answer is faster than the code in my alternative solution below. [It was, consistently, 4 times faster for me instead of 10 times faster as KERR claims; but still faster.]

But note tho that for the view objects returned by Get-View, the Guest.IPAddress property consists of a single address and it may not even be an address for a NIC (it may be, e.g. a VPN connection).

Here's a one-line (tweaked) version of bxm's code:

Get-View -ViewType VirtualMachine | ?{ $_.Guest.IPAddress -eq "1.2.3.4" }

and here's a version that should check all of the NIC addresses:

Get-View -ViewType VirtualMachine | ?{ ($_.Guest.Net | %{ $_.IpAddress }) -contains "1.2.3.4" }

where "1.2.3.4" is the IP address for which you want to find the corresponding VM.

Note that my version is slightly different than bxm's. bxm's version effectively ensures that any matching VMs only have the specified IP address assigned and no others (or, rather, it would if the Guest.IPAddress property was an array). My version only ensures that the VM has that specified address, regardless of any other IP addresses it's assigned.

Get-VM

Here's my adaptation of the code at the link provided by StackUser_py's answer:

Get-VM | Where-Object -FilterScript { $_.Guest.Nics.IPAddress -contains "1.2.3.4" }

Note tho that these two solutions return different results, the first an (array of) VirtualMachine (objects), and the second a UniversalVirtualMachineImpl. However, calling Get-VM and passing it the name of the VM returned by the first solution does not significantly alter the duration.

like image 185
Kenny Evitt Avatar answered Oct 19 '22 13:10

Kenny Evitt


I got the command working with a small tweak to the objects used, like so:

$list = Get-View -ViewType VirtualMachine | Select name,@{N='IP';E={[string]::Join(',',$_.Guest.ipaddress)}}
$list | ?{ $_.ip -eq "1.2.3.4" }
like image 2
bxm Avatar answered Oct 19 '22 13:10

bxm