0

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

1
  • 1
    This will add the entry multiple times if you run it multiple times. You also want to remove the entry when not at that network. You don't want to script this yourself. Check superuser.com/questions/663183/… for example. Commented Jun 12, 2015 at 9:32

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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%

1 Comment

first thing that comes to mind is just have the script copy 1 of 2 different versions of the hostsfile depending on if error level is 1 or not. this saves you the trouble of format issues within the hostfile and need to clear it after.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.