0
votes

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) }
1
And what is the problem with that code?Nico Haase
A quick search threw up quite a few examples of how to manipulate the hosts file. For example: PsHosts. I've not used this particular one, but it's worth a try.boxdog
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 lineItchydon
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
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 tactItchydon

1 Answers

1
votes

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" 
}