Hi,
How can add new record (IP address and host name) to the hosts file of the current (localhost) machine?
It is very appreciated to send me a sample script.
Regards,
Bader
$ip = "127.0.0.1"
$xhost = "localhost"
"`n`t{0}`t{1}" -f $ip, $xhost | out-file C:\Windows\System32\drivers\etc -append
Thank you very much for the reply,
I tried your script (modified):
"`n`t{0}`t{1}" -f $ip, $xhost | out-file C:\Windows\System32\drivers\etc\hosts -append
But... the inserted line is displayed with spaces as shown below:
1 2 7 . 0 . 0 . 1 l o c a l h o s t
Where the record is intended to be displayed as below (without spaces):
127.0.0.1 localhost
Can you please, send me the modified script that cleans the spaces?
These values are being assigned with the spaces to the variables I guess.
You can remove the spaces doing this:
"`n`t{0}`t{1}" -f $ip.replace(" ",""), $xhost.replace(" ","") | out-file C:\Windows\System32\drivers\etc\hosts -append
Thanks for the reply,
I tried you modified script, but the spaces still displayed,
Also, how can I allways add the new record in a new line?
use the function in this link
http://msmvps.com/blogs/richardsiddaway/archive/2011/10/24/hosts-file-add-a-record.aspx
The spaces are because of the default encoding used by out-file
add
-Encoding ASCII
to the end of the command
1) Regarding the add-hostfilecontent function (http://msmvps.com/blogs/richardsiddaway/archive/2011/10/24/hosts-file-add-a-record.aspx), I got the following error message:
Unexpected token 'Set-Content' in expression or statement.At line:6 char:58+ $data += "$IPAddress $computer" Set-Content <<<< -Value $data -Path $file -Force -Encoding ASCII } + CategoryInfo : ParserError: (Set-Content:String) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken
2) How can I read, update and remove records from the hosts file?
Please, I need your help