Esses scripts excluem qualquer coisa depois de 127.0.0.1 localhost
e a salvam novamente no arquivo. Caso suas condições resolvam ser verdadeiras, a nova entrada é injetada antes que o arquivo seja gravado no disco.
O código:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
$ipAdresses = Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object {$_.IPAddress.length -gt 0} | Select-Object -Property 'IPAddress' -First 1
$ip = $ipAdresses.IPAddress[0]
$hst = $env:COMPUTERNAME
$hostFilePath = "$($env:windir)\system32\Drivers\etc\hosts"
$hostfile = Get-Content -Path $hostFilePath
$newHostFileEntry = "{0} {1}" -f $ip, $hst
# Delete all text after what is defined as $matchString
$lastIndexOfNewArray = 0
$matchString = '127.0.0.1\s+localhost'
for ($index = 0; $index -lt $hostfile.Count; $index++) {
if ($hostfile[$index] -match $matchString) {
$lastIndexOfNewArray = $index
break
}
}
$newHostFileContent = $Hostfile[0..$lastIndexOfNewArray]
# Adds entry for local IP address if conditions resolve to $true
if ($newHostFileContent -notcontains "127.0.0.2 hostname1" -and
(-not($newHostFileContent -like $newHostFileEntry))) {
$newHostFileContent = New-Object System.Collections.ArrayList(,$newHostFileContent)
$newHostFileContent.Add($newHostFileEntry) > $null
}
Out-File -Encoding UTF8 -FilePath $hostFilePath -InputObject $newHostFileContent -Append:$false -Confirm:$false