I wrote this function for deployment scripts which takes the IP address and does a lookup in an external file. Here's the code...
Function Get-NetworkName
{
param($vmip)
$ip = $vmip
$ipArray = $ip.Split(".")
$subnet = $ipArray[0] + "." + $ipArray[1] + "." + $ipArray[2]
$path = "vlanmapping.txt"
$vlanhash = ConvertFrom-StringData -StringData ([io.file]::ReadAllText($path))
$networkname = $vlanhash.Get_Item($subnet)
return $networkname
}
$vmname = "my_vm"
$vmip = "10.10.1.100"
Get-VM -name $vmname | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName (Get-NetworkName($vmip)) -confirm:$false
#Contents of vlanmapping.txt
#10.10.10=VLAN1
#10.10.20=VLAN2
#10.10.30=VLAN3
BE CAREFUL! This works well with a VM with 1 NIC only. The Get-NetworkAdapter cmdlet returns all NICs so all NICs will have their Network set.
Hope ok.