Create batch script to edit host file by network connection

1.6k Views Asked by At

I want to use this batch script to add new entries into my host file automatically by using windows batch.

I want to edit host file only when i m in office. I want to say like that: if(network name=='OfficeWifi') do changes...

@echo off

set hostspath=%windir%\System32\drivers\etc\hosts
// if(network name=='OfficeWifi')
echo 81.155.145.48 ns1.intranet.de >> %hostspath%

exit

thx for your help

2

There are 2 best solutions below

0
On BEST ANSWER

You can get the network name (SSID) of the currently connected wireless network using the following batch file:

for /f "tokens=3" %%a in ('netsh wlan show interface ^| findstr /r "^....SSID"' ) do @echo %%a

So your batch file would look like:

@echo off
set hostspath=%windir%\System32\drivers\etc\hosts
for /f "tokens=3" %%a in ('netsh wlan show interface ^| findstr /r "^....SSID"' ) do (
  if "%%a"=="OfficeWifi" echo 81.155.145.48 ns1.intranet.de >> %hostspath%
)
exit

Sources FOR /F, NETSH (Network Shell)

1
On

to make it simple you could just add :

@echo off

set hostspath=%windir%\System32\drivers\etc\hosts
ping "name of office DC" 
if errorlevel 1 quit    
if not errorlevel 1 echo 81.155.145.48 ns1.intranet.de >> %hostspath%