Host File Append Script.

Hello All,

I got a script which helps me in appending the host files on multiple servers but my requirement is bit different and the new entries should append under Networker configuration below, whereas now the entries are getting appended at the bottom of the Host file.

Below is the sample output of host file (for now the new entries are getting appended below #Control-M whereas i want them to be appended under #Networker Configuration.

NetWorker Configuration

#########################
192.168.244.50 pfrxbnw31
192.168.244.121 pfrxbdd41

Control-M

#########################
10.61.199.146 gerctmpas73
10.61.199.143 gerctmpem71

 

Below is my script how can i modify it so the entries should append right exactly at the bottom of #Networker Configuration

$ErrorActionPreference=“stop”
$Error_log_File=“C:\Temp\InError.txt”
$serverNames=“C:\Temp\serverlist.txt”
$InputFile=“C:\Temp\entries.txt”
$file=“c$\Windows\System32\drivers\etc\hosts”
$backupFileName=“c$\Windows\System32\drivers\etc\hosts_script_backup”

$hostEntries=Get-Content “C:\Temp\entries.txt”
If(Test-Path $Error_log_File)
{
Remove-Item $Error_log_File
}
New-Item $Error_log_File -ItemType file | Out-Null

If(Test-Path $InputFile) {

$servers=Get-content $serverNames
Foreach ($computer in $servers) {

try {

$hostfilePath=Join-Path “\$computer” -ChildPath $file
$backupPath=Join-Path “\$computer” -ChildPath $backupFileName
Copy-Item $hostfilePath -Destination $backupPath
Add-Content $hostFilePath -Value $hostEntries
Write-host “Processed $computer” -ForegroundColor Cyan

}

catch {

write-host “Error processing $computer” -ForegroundColor Red
Write-Output “$computer” | Out-File $Error_log_File -Append

}
}
}
Else {
write-host “InputFile: $InputFile Not Found” -BackgroundColor Red

}

Aatif18,

I saw that you posted this question also in the Microsoft forum. Regardless of the fact that you did not format your code as code in both forums, let me ask you some questions - and you should answer these questions for yourself - not for me:

Do you run an environment with an Active Directory?

Is it a recommended procedure to use hosts files on local machines?

If you want to use your error prone and hard to maintain approach anyway - how many host entries do you want to add to your files?

From a pure technical point of view - does it really matter where these entries are in the hosts file?

Hai @aatif - To format your code please go through below instructions.

https://powershell.org/forums/topic/read-me-before-posting-youll-be-glad-you-did/

 

 

 

Thank you Prasoon for your reply.

I think I didn’t read it thoroughly anyways will be taking care in the future as this is my maiden post.