How to Set Up a Static IP Address for your Hyper-V VM
Overview
The Problem
In this blog, you will learn how to assign a static IP address to your virtual machine (VM) in Hyper-V, so that you can easily connect to it with RDP, SSH, or VScode. You will also learn why the default switch does not allow you to do that, and how to create a new internal switch with NAT. This is a useful skill for anyone who works with Hyper-V and wants to avoid the hassle of changing IP addresses every time they restart their VM.
With the default switch config you cannot assign a static ip.
The default switch is hyper-v is not meant to have a static IP.
Solution
One possible solution is to set up a new internal switch with NAT and connect the VMs to it. This example uses the subnet 192.168.98.0/24 for the virtual network and the IP address 192.168.98.1 as the gateway.
Here are some powershell commands:
Create a new Internal switch
1New-VMSwitch -SwitchName "SwitchName" -SwitchType Internal
Get the Interface Index. Take note of its ifIndex to use in the next step.
1Get-NetAdapter
Assign ip to the switch. This is the default GW. Assign it to the interface index you find above.
1New-NetIPAddress -IPAddress 192.168.98.1 -PrefixLength 24 -InterfaceIndex <INDEX>
Create a NAT gateway
1New-NetNat -Name MyNATnetwork -InternalIPInterfaceAddressPrefix 192.168.98.0/24
Here the all the commands in one block:
1New-VMSwitch -SwitchName "SwitchName" -SwitchType Internal
2Get-NetAdapter
3New-NetIPAddress -IPAddress 192.168.98.1 -PrefixLength 24 -InterfaceIndex <INDEX>
4New-NetNat -Name MyNATnetwork -InternalIPInterfaceAddressPrefix 192.168.98.0/24
Next, you need to connect the VM to the new internal switch. Then, you need to set up the correct IP configuration for the VM. For example:
1ip 192.168.98.2
2mask 255.255.255.0
3gateway 192.168.98.1
4dns 8.8.8.8
Unlike the Default Switch, there is not automatic network configuration trough DHCP, so inside the VM you have to configure a static ip for example 192.168.98.2.
You can now connect to the VM using RDP from your host machine. Just enter the IP address of the VM in the Remote Desktop Connection window. If you have configured SSH in the VM, you can also edit files remotely with VSCode. But that is a topic for another blog post.
Source: Guide from Microsoft