这是为啥,怎么解决,每次都添加到人家地址后面无语了,可有什么办法解决是脚本本身问题吗?

关注让 “紫雾凌寒” 来帮你回答,本回答结合 DeepSeek
如果还有问题,请评论或点击头像私信,如果有帮助到您, 请关注、采纳、点赞
@echo off
setlocal enabledelayedexpansion
set "hostsfile=%systemroot%\system32\drivers\etc\hosts"
set "newentry=1.2.3.4 example.com"
:: 检查是否已存在该记录
set found=0
for /f "tokens=1,2*" %%i in ('type "%hostsfile%" ^| findstr /i /c:"%newentry%"') do (
set found=1
)
:: 如果不存在,则添加
if %found% equ 0 (
echo %newentry% >> "%hostsfile%"
echo Added %newentry% to hosts file
) else (
echo %newentry% already exists in hosts file
)
hostsfile变量为系统HOSTS文件路径。newentry变量为要添加的记录。for /f循环结合findstr命令检查HOSTS文件中是否已存在该记录。如果存在,found变量会被设为1;不存在则添加新记录。$hostsPath = "$env:SystemRoot\System32\drivers\etc\hosts"
$newEntry = "1.2.3.4 example.com"
$content = Get-Content $hostsPath
if ($content -notcontains $newEntry) {
$content += $newEntry
$content | Out-File -FilePath $hostsPath -Encoding ASCII
Write-Host "Added $newEntry to hosts file"
} else {
Write-Host "$newEntry already exists in hosts file"
}
- **缺点**:需要系统安装PowerShell,对于没有安装PowerShell的系统不可用,且语法相对批处理更复杂一些。
希望以上解答对您有所帮助。如果您有任何疑问,欢迎在评论区提出。