Adding a new record to the hosts of the current host

rated by 0 users
This post has 7 Replies | 2 Followers

Top 75 Contributor
Posts 35
Bader Posted: 05-17-2012 2:11 AM

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

Top 25 Contributor
Posts 287
Top Contributor

$ip = "127.0.0.1"

$xhost = "localhost"

"`n`t{0}`t{1}" -f $ip, $xhost | out-file C:\Windows\System32\drivers\etc -append

Top 75 Contributor
Posts 35

Hi,

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?

Regards,

Bader

Top 25 Contributor
Posts 287
Top Contributor

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

Top 75 Contributor
Posts 35

Hi,

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?

Regards,

Bader

Top 25 Contributor
Posts 296
Microsoft MVP
Top Contributor

The spaces are because of the default encoding used by out-file

add

-Encoding ASCII

to the end of the command

Top 75 Contributor
Posts 35

Hi,

Thank you very much for the reply,

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

Regards,

Bader

Page 1 of 1 (8 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.