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?
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.
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With