$ErrorActionPreference = "Stop" $hosts = "$($env:windir)\System32\drivers\etc\hosts" while ($true) { Write-Host -ForegroundColor Yellow "Scanning for Virtual Machines" $content = Get-Content $hosts Get-VM | ForEach-Object ` { $vm = $_ $regex = '^\s*\S+\s+' + $vm.Name + '$' Write-Host -ForegroundColor Magenta "VM: $($vm.Name)" $ips = @($vm.NetworkAdapters | Select -ExpandProperty IPAddresses) if ($ips.Count) { $matches = $content | Select-String -Pattern $regex | ForEach-Object { $_.Line } | Out-String $wanted = $ips | ForEach-Object { $_ + ' ' + $vm.Name } | Out-String if ($matches -ne $wanted) { $content = ($content | Select-String -Pattern $regex -NotMatch | ForEach-Object { $_.Line } | Out-String).Trim() $content += "`n" + $wanted } } } $content | Set-Content "${hosts}.tmp" if ((Get-FileHash "$hosts").Hash -ne (Get-FileHash "${hosts}.tmp").Hash) { Move-Item -Path "${hosts}.tmp" -Destination "$hosts" -Force Write-Host -ForegroundColor Yellow "Hosts file updated!" } Write-Host -ForegroundColor DarkGray "Sleeping..." Start-Sleep -Seconds 60 Write-Host }