0

I am looking to append windows host file get current dynamic ip and map it to a host name irrespective of current ip address. i am getting below error

===============================================
Add-Content : A positional parameter cannot be found that accepts argument 'hostname1'. At C:\Users\Opps\Desktop\power\New Text Document.ps1:6 char:3 + {ac -Encoding UTF8 -value "$($env:windir)\system32\Drivers\etc\hosts ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Add-Content], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.AddContentCommand
================================================================================

Script :

$ip=get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1} 
$ip.ipaddress[0]
$hst = $env:COMPUTERNAME

Set-ExecutionPolicy -ExecutionPolicy Unrestricted If ((Get-Content "$($env:windir)\system32\Drivers\etc\hosts" ) -notcontains "127.0.0.2 hostname1") 
 {ac -Encoding UTF8 "$($env:windir)\system32\Drivers\etc\hosts" ($ip.ipaddress[0]) ($hst) }
ra8ul
  • 1
  • 3
  • And what is the problem with that code? – Nico Haase Jun 23 '18 at 07:29
  • A quick search threw up quite a few examples of how to manipulate the hosts file. For example: [PsHosts](https://github.com/richardszalay/pshosts). I've not used this particular one, but it's worth a try. – boxdog Jun 23 '18 at 07:45
  • 1
    Change the add-content line to `{ac -Encoding UTF8 "$($env:windir)\system32\Drivers\etc\hosts" "$($ip.ipaddress[0]) $hst" }` and move the `if` statement down a line – Itchydon Jun 23 '18 at 08:40
  • Thank you ltchydon its working now this seems to be adding multiple duplicate or new ip to host file can we append the same line instead of appending new line every time this script is run. – ra8ul Jun 23 '18 at 11:02
  • The hostfile needs to contain one per line, so I am assuming you want to check before duplicating an entry. I'll add it as an answer so the formatting remains in tact – Itchydon Jun 23 '18 at 17:38
  • Latest script works from powershell editor not from right click "run with powershell" from editor stops duplicate same IP address entries but it has created different ip host entries since i am connecting to multiple router with a new ip and subnet. Can we do one thing i have removed comment for local host 127.0.0.1 localhost. Can we insert new entries after this line localhost irrespective of next – ra8ul Jun 24 '18 at 09:14
  • @ra8ul - I don't really understand your issue. It checks for the hostname/ipaddress combination, only if the combination is not found will it create the entry, but yes you can add more conditions to the `if` statement as required – Itchydon Jun 24 '18 at 09:30
  • @ltchy i have two routers for internet connection the IP address from one router dhcp to my system will be different from another router. When i run script repeatedly if i am connected router A there are no duplicate entries but if i change to router B both router A and router B resolved ip remains in the host file. Therefore i was requesting to change the logic to check 127.0.0.1 localhost in the last line of host file after i removed the comments.Remove any line after above entry which is last line and add the fetched IP. Thank you in advance. – ra8ul Jun 25 '18 at 03:52
  • @ra8ul - you are moving the goal posts by asking for something different from your original request. You are no longer just talking about appending the file, but replacing contents within the file - different logic. May I suggest you raise this as another question – Itchydon Jun 25 '18 at 07:14

1 Answers1

1

Add-Content is expecting a string as a value hence to change the type we need to encapsulate the value in quotes. To access an objects property e.g. $ip.ipaddress[0] while in quotes, in order for the text to not be treated literally, we must wrap it in brackets with a preceding dollar sign "$(...)" officially known as a subexpression operator (see mklement0's explanaton) . To ensure we are not duplicating an entry we run a quick check for the entry with the if statement only proceeding to add-content if both conditions of the if statement are met

$ip = get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1} 
$ip.ipaddress[0]
$hst = $env:COMPUTERNAME
$hostfile = Get-Content "$($env:windir)\system32\Drivers\etc\hosts"
Set-ExecutionPolicy -ExecutionPolicy Unrestricted 
if ($hostfile -notcontains "127.0.0.2 hostname1" -and 
    (-not($hostfile -like "$($ip.ipaddress[0]) $hst"))) {
    Add-Content -Encoding UTF8 "$($env:windir)\system32\Drivers\etc\hosts" "$($ip.ipaddress[0]) $hst" 
}
Itchydon
  • 2,572
  • 6
  • 19
  • 33
  • Suggestion: Might want to add a check if the entry exists but not commented. – Sid Jun 24 '18 at 04:53
  • @RohinSidharth - Thanks for the suggestion - the script already checks if the entry exists with the following condition of the `if` statement `(-not($hostfile -like "$($ip.ipaddress[0]) $hst")))` or am I misunderstanding you? – Itchydon Jun 24 '18 at 08:43
  • It is not a big deal but there is a chance that an entry may be present but commented with a # at the beginning of the line. Since that condition only checks if the entry is present and does not add one if it is, but if it is commented, then the script does nothing. Like I said, it's a minute possibility. No big deal. – Sid Jun 25 '18 at 07:26
  • I get you Rohin - I can tackle that quite easily with a wildcard search by adding an asterisk and changing the condition slightly similar to `(-not($hostfile -like "*$($ip.ipaddress[0]) $hst"))) {` However O.P. keeps moving the goal posts so I'll hang fire for now – Itchydon Jun 25 '18 at 07:44