我希望附加 windows 主机文件获取当前动态 ip 并将其映射到主机名



我希望附加Windows主机文件获取当前动态IP并将其映射到主机名,而不考虑当前IP地址。 我得到以下错误

=========================================================================================================================================================================================================

==
at C:\Users\Opps\Desktop\power\New Text Document.ps1:6 char:3 + {ac -Encoding UTF8 -value "$($env:windir(\system32\Drivers\etc\hosts ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 类别信息: 无效参数: (:) [添加内容], 参数绑定异常 + FullQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Command.AddContentCommand
=

===========================================================================================================================================================================================================================================================================================================================

脚本:

$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)system32Driversetchosts" ) -notcontains "127.0.0.2 hostname1") 
{ac -Encoding UTF8 "$($env:windir)system32Driversetchosts" ($ip.ipaddress[0]) ($hst) }

>Add-Content期望一个字符串作为值,因此要更改我们需要将值封装在引号中的类型。 访问对象属性,例如$ip.ipaddress[0]在引号中,为了使文本不按字面意思处理,我们必须将其括在括号中,前面的美元符号"$(...)"正式称为子表达式运算符(参见 mklement0 的解释(。 为了确保我们不会重复条目,我们运行该条目的快速检查,if语句仅在满足if语句的两个条件时才继续add-content

$ip = get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1} 
$ip.ipaddress[0]
$hst = $env:COMPUTERNAME
$hostfile = Get-Content "$($env:windir)system32Driversetchosts"
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)system32Driversetchosts" "$($ip.ipaddress[0]) $hst" 
}

最新更新