hyperv2hosts
hyperv2hosts copied to clipboard
Powershell
Hi, I create a pure powershell script for the whole process. Please, publish it if you want.
BR, Tamas
The code:
function Update-HostsFileWithVMIP {
param (
[Parameter(Mandatory=$true)]
[string]$VMName
)
$ipInfo = Get-VMNetworkAdapter -VMName $VMName | Where-Object { $_.IPAddresses -ne $null } | Select-Object -ExpandProperty IPAddresses
if (-not $ipInfo) {
Write-Error "No IP address found for VM $VMName."
return
}
$ipAddress = $ipInfo[0]
$hostsPath = "C:\Windows\System32\drivers\etc\hosts"
$hostsContent = Get-Content $hostsPath
if ($hostsContent -match "$VMName.vm") {
$hostsContent = $hostsContent -replace "^\s*\d+\.\d+\.\d+\.\d+\s+$VMName.vm$", "$ipAddress $VMName.vm"
} else {
$hostsContent += "`n$ipAddress $VMName.vm"
}
$hostsContent | Out-File $hostsPath -Encoding ASCII -Force
Write-Output "The hosts file has been successfully updated with the new IP address for $VMName.vm."
}
Update-HostsFileWithVMIP -VMName "WM_NAME"
The script written by ChatGPT