Скрипт для перезагрузки сетевого адаптера windows

Очень часто при работе по удаленке надо передернуть сетевой кабель или отключить и включить сетевой адаптер. Но раз мы не можем это сделать физически, приходится просить кого-то это сделать или изощряться такими способами. В Linux это происходит легко, через ssh вбиваем ifdown eth0 & ifup eth0 и всё норм. В Windows приходится провернуть следующее... Создаём bat-ник,

Очень часто при работе по удаленке надо передернуть сетевой кабель или отключить и включить сетевой адаптер. Но раз мы не можем это сделать физически, приходится просить кого-то это сделать или изощряться такими способами. В Linux это происходит легко, через ssh вбиваем ifdown eth0 & ifup eth0 и всё норм. В Windows приходится провернуть следующее…

Создаём bat-ник, вписываем туда следующий скрипт обязательно в кодировке ANSI

netsh interface set interface name="Подключение по локальной сети" admin=DISABLED

ping 127.0.0.1 -n 6 > nul

netsh interface set interface name="Подключение по локальной сети" admin=ENABLED

и запускаем от имени администратора.

где «Подключение по локальной сети» — это название сетевого адаптера в вашей Windows. Оно может называться «Подключение по локальной сети 2» или «Подключение по локальной сети 3«.  Я для удобства переименовал подключения в LAN, WiFi, Internet, Router или Bluetooth.

Замечания: работает не только в Windows 7, но также и в Windows 8 и Windows 10.

P.S. один раз скрипт не заработал, пришлось рано утром ехать на объект, так что применяем на свой страх и риск

Отблагдарить автора статьи также можно переводом, +100 вам в карму!

 bat windows скрипт

OS: Vista enterprise

When i switch between my home and office network, i always face issues with getting connected to the network. Almost always I have to use the diagnostic service in ‘Network and sharing center’ and the problem gets solved when i use the reset network adapter option.

This takes a lot of time (3-4 min) and so i was trying to find either a command or a powershell script/cmdlet which i can use directly to reset the network adapter and save myself these 5 mins every time i have to switch between the networks. Any pointers?

dsolimano's user avatar

dsolimano

8,7303 gold badges48 silver badges63 bronze badges

asked Oct 16, 2008 at 3:00

Mohit's user avatar

1

You can use WMI from within PowerShell to accomplish this. Assuming there is a network adapter who’s device name has Wireless in it, the series of commands might look something like the following:

$adaptor = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*Wireless*"}
$adaptor.Disable()
$adaptor.Enable()

Remember, if you’re running this with Window’s Vista, you may need to run the PowerShell as Administrator.

answered Oct 16, 2008 at 5:09

Scott Saad's user avatar

Scott SaadScott Saad

17.8k11 gold badges63 silver badges84 bronze badges

2

Zitrax’s answer:

netsh interface set interface "InterfaceName" DISABLED
netsh interface set interface "InterfaceName" ENABLED

was 99% of what I was looking for. The one piece of information that s/he left out, though, was that these commands have to be run as an administrator. Either run cmd.exe as an admin and type them in, or store them in a batch file, and then run that file as admin by right clicking on it and choosing «Run as Administrator» from the context menu.

answered Nov 30, 2014 at 3:56

Andrew C's user avatar

Andrew CAndrew C

1111 silver badge2 bronze badges

1

See this article from The Scripting Guys, «How Can I Enable or Disable My Network Adapter?»

tl/dr:

Restart-NetAdapter   -Name "Your Name Here"

You can get the list using

Get-NetAdapter

kͩeͣmͮpͥ ͩ's user avatar

answered Oct 16, 2008 at 4:02

Mike L's user avatar

Mike LMike L

4,6535 gold badges35 silver badges52 bronze badges

2

You can also try this in a .BAT or .CMD file:

ipconfig /release
ipconfig /renew
arp -d *
nbtstat -R
nbtstat -RR
ipconfig /flushdns
ipconfig /registerdns

These commands should do the same things as the ‘Diagnose and Repair’ for the network adapter, but is WAY faster!

Let me know if this helps!
JFV

answered Oct 16, 2008 at 4:08

JFV's user avatar

JFVJFV

1,8036 gold badges24 silver badges36 bronze badges

2

What worked for me:

netsh interface show interface

to show the interface name which for me was «Ethernet 2» and then:

netsh interface set interface "Ethernet 2" DISABLED
netsh interface set interface "Ethernet 2" ENABLED

answered Mar 5, 2014 at 10:00

Zitrax's user avatar

ZitraxZitrax

18.4k19 gold badges85 silver badges107 bronze badges

The following command worked for me (on Server 2012 R2):

Restart-NetAdapter -Name "Ethernet 2"

Replace «Ethernet 2» with the name of your adapter.

Note: To create a PS script: create a new document in Notepad, save is as script.PS1, insert the line above and save. Right click the file -> Run with PowerShell.

For more see this technet article.

answered Sep 7, 2016 at 13:44

Leigh's user avatar

LeighLeigh

1,4952 gold badges20 silver badges42 bronze badges

The post of Scott inspired me to write a very small C# / .Net console application, that uses System.Management. You can name the adapter, that you want to restart, as a command line parameter. The code shows some basics about handling devices, that could be useful for others too.

using System;
using System.Management;

namespace ResetNetworkAdapter
{
  class Program
  {
    static void Main(string[] args)
    {
      if (args.Length != 1)
      {
        Console.WriteLine("ResetNetworkAdapter [adapter name]");
        Console.WriteLine("disables and re-enables (restarts) network adapters containing [adapter name] in their name");
        return;
      }

      // commandline parameter is a string to be contained in the searched network adapter name
      string AdapterNameLike = args[0];

      // get network adapter node 
      SelectQuery query = new SelectQuery("Win32_NetworkAdapter");
      ManagementObjectSearcher searcher =  new ManagementObjectSearcher(query);
      ManagementObjectCollection adapters = searcher.Get();

      // enumerate all network adapters
      foreach (ManagementObject adapter in adapters)
      {
        // find the matching adapter
        string Name = (string)adapter.Properties["Name"].Value;
        if (Name.ToLower().Contains(AdapterNameLike.ToLower()))
        {
          // disable and re-enable the adapter
          adapter.InvokeMethod("Disable", null);
          adapter.InvokeMethod("Enable", null);
        }
      }
    }
  }
}

answered Mar 30, 2011 at 14:02

Claudio Maranta's user avatar

This is what I use on PowerShell version 5.0.10586.122 Windows 10 Home. This needs to be run as an administrator:

Restart-NetAdapter -Name "ethernet"

To run this as an administrator without having to «Turn off UAC» or «R-Click-> Run as administrator»: (This is a one time task)

  • Put the above Restart-NetAdapter -Name "ethernet" into a .ps1 file
  • Create a new shortcut (R-Click on .ps1 file > Create Shortcut)
  • On the Shortcut, R-Click > Properties > Shortcut > Target > (Append Powershell.exe to precede the Location/filename as shown below.
    Also enclose the Location/filename with double quotes(«), also shown below.

enter image description here

  • On the Shortcut, R-Click > Properties > Shortcut > Advanced > «Run As Administrator»(Check this Check box)

Now every time you run the shortcut, you will need to just click «Yes» on the UAC screen and it will reset the adapter you’ve specified in the .ps1 file.

To get the names of the available adapters using PowerShell(WiFi, LAN etc.,):

Get-NetAdapter

answered Mar 19, 2016 at 11:20

Santa's user avatar

SantaSanta

1656 bronze badges

1

You can also use the Microsoft utility devcon.exe.

First, run devcon listclass net to find your Device ID.

Then use this device ID in this command: devcon restart PCIVEN_16* (using the '*' wildcard to avoid needing to enter the entire ID string).

answered Mar 7, 2010 at 10:45

Andrew Strong's user avatar

Andrew StrongAndrew Strong

4,2732 gold badges23 silver badges26 bronze badges

You can also restart a NIC using wmic command:

Get interface ID:

C:>wmic nic get name, index 

Disable NIC (InterfaceID:1):

wmic path win32_networkadapter where index=1 call disable

Enable NIC (InterfaceID:1):

wmic path win32_networkadapter where index=1 call enable

Source: http://www.sysadmit.com/2016/04/windows-reiniciar-red.html

answered Apr 19, 2016 at 10:44

Lunudeus1's user avatar

You could also try netsh commands. Example:

netsh wlan disconnect && netsh wlan connect [ONE OF YOUR WLAN PROFILES]

You can get a list of those «profiles», using:

netsh wlan show profiles

answered Dec 29, 2012 at 21:29

Protector one's user avatar

Protector oneProtector one

6,6494 gold badges59 silver badges81 bronze badges

1

ipconfig /flushdns

ipconfig /renew

Are the 2 cmdlets I use to refresh my connection. You don’t necessarily need to power cycle the router to re-gain a strong signal( I know power cycling clears the router’s memory but that’s really it).

answered Jul 11, 2014 at 18:55

user3830646's user avatar

1

Thanks for the Info that it can be done with netsh.
I wrote a simple «Repair.bat» script:

@echo off
netsh interface set interface "%1" DISABLED
netsh interface set interface "%1" ENABLED

Just call it with the name of the NIC, renamed as i.e. «WLAN» so I does not have spaces, type «Repair WLAN» into cmd does the trick.
I’ll place it into system32 and make a task of it or see how to integrate it into the network context menu…

answered May 30, 2016 at 22:22

Alahndro's user avatar

There are many things that you can do with Windows and batch scripting. Previously, we went through the basics of creating a batch file, and appending a simple “Hello World” command within it. Now, we are going to do something a little more complex that involves toggling our network adapter on and off.

If you haven’t already, take a look at this guide in order to have an understanding on how batch scripting works. First, we are going to take a look at the commands we will be inserting into our batch script.

Open up Command Prompt by going to the Start Menu->Search, and then type the word “cmd” into the search box. You will need to right-click on it and select “Run as administrator”. Click to confirm.

This particular command requires us to run as an administrator due to the face that it is a system command. This will always be the case when running your batch script. Now, we are going to need the name(s) of the network adapters that we will be disabling and re-enabling in our command. Type in the following in Command Prompt:

ipconfig

You are now given a list of network adapters currently installed on your computer. We want the one with an “IPv4 Address”, “Subnet Mask”, and a “Default Gateway” already established. This adapter is already connected to your LAN and getting you to the internet. For example, if we have a WiFi adapter, it will display Wireless LAN adapter “Wi-Fi” and Ethernet adapter “Ethernet”. That name will be used in our command.

Now we will be typing in the following into Command Prompt:

netsh interface set interface ADAPTER_NAME disable

The command has been successfully executed as you can see above.

Also if you go into your network adapter settings in Control Panel, you will notice that it is now disabled. Of course if this is your primary adapter, then you currently do not have an internet connection and will want to re-enable it by typing the following into Command Prompt:

netsh interface set interface ADAPTER_NAME enable

Your network adapter should now be re-enabled. One thing to note though, there’s a way to execute both commands within one line by simply typing in the following:

netsh interface set interface ADAPTER_NAME disable && netsh interface set interface ADAPTER_NAME enable

“&&” was appended into the middle of both commands. This tells Command Prompt to execute each command one-by-one through a single line. Now that we know how to use these commands, lets go ahead and implement them into a batch file.

Open Notepad. Type in the following into the box:

@ECHO OFF
cls
netsh interface set interface Ethernet disable
netsh interface set interface Ethernet enable
pause

Where “Ethernet” is the name of the network adapter you want to use. In most cases, it is given that for a generic name followed by “Ethernet 2” and so on and so forth. Now, save it as “netsh.bat” and make sure the “Saves as type:” is set to “All Files”.

Now, since we will always need to run our batch script as an administrator, we are going to create a shortcut to it. Right-click on the batch file and select “Create shortcut”. A new shortcut will be created at the end of the file’s folder or your “Desktop” depending on folder permissions.

Right-click on the shortcut and click “Properties”.

Click on “Advanced…” and check the box that says “Run as administrator”. Click “OK” and then click “Apply” in the properties window. Close it.

Run your batch script by click on the shortcut file. To get a better look of your script in action, open up the network adapters window.

If you’re seeing the network adapter disable and then re-enable itself, then your batch script has successfully ran without any issues. You are now able to use this script on a whim in order to fix any internal networking issues with a click of a “button”!

Приветствую. уже не первый день бьюсь с автоматизацией, задача перезагрузка адаптера интернет по проводу.
Пытался релизовать .bat через проверку пинга и команды выключения и включения адаптера, но проверку пинга он проводил до тех пор, пока я сам не выдернул провод,ну или не сменил мак провайдера, чтобы создать ситуацию отключения. батник закрывался. хотя он должен был перезагружать адаптер до тех пор пока не включится интернет, то есть проверять пинг и пока он не откликнется перезагружать адаптер. Знающие люди, помогите решить проблему.

@echo off
:LOOP
ping 8.8.8.8 -n 2
if errorlevel 1 (
echo %Errorlevel%
echo %date% %time% >> C:log.txt
netsh interface set interface name=»Ethernet» DISABLE
netsh interface set interface name=»Ethernet» ENABLE
exit
) ELSE (
echo
)
timeout /T 30
goto LOOP

пробовал подглянуть в wifi, но не дало результата

Sometimes, the domain based Windows server started but its network adapter switched into the public mode. Yup, the real nightmare, especially if you configured a very restrictive firewall rules. And you’re using the rigid firewall rules in the public mode, right?

The easiest way to switch such NIC back to the domain mode is to restart (disable and enable) it. Indeed! It’s so easy to perform named operations when you’re on the console of such server. What to do if you only have the remote connection?

It’s time for the mighty Jedi tricks and the command line Kung-Fu!

The power shell contains more than 2,500 different commands and you can perform virtually any task with a few commands. And all those commands are well documented on this Web page.

Server booted with NIC in the public mode

One of the servers worked, but its NIC was in the public mode. You can find that if you open the Network & Internet settings GUI.

clip_image002

We can see that the network adapter named Team1 is marked as the Public network. Now we knew the right adapter name.

Checking existing network adapters

I opened the administrative power shell window and typed already familiar command Get-NetAdapter.

PS C:WINDOWSsystem32> Get-NetAdapter

Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
----                      --------------------                    ------- ------       ----------             ---------
Team1                     Microsoft Network Adapter Multiplexo...      18 Up           E0-CB-4E-0C-4A-06         2 Gbps
Ethernet 4                Intel(R) PRO/1000 PT Dual Port Ser...#2      17 Disconnected 00-15-2A-6E-40-61          0 bps
Ethernet                  Broadcom NetXtreme Gigabit Ethernet          11 Up           E0-CB-4E-0C-49-34         1 Gbps
Ethernet 2                Broadcom NetXtreme Gigabit Ethernet #2        6 Up           E0-CB-4E-0C-4A-06         1 Gbps
Ethernet 3                Intel(R) PRO/1000 PT Dual Port Serve...       3 Disconnected 00-15-2A-6E-40-60          0 bps


PS C:WINDOWSsystem32>

We can see the list of all adapters. This is the same step I already used in this post.
We can see that we have the virtual adapter named Team1 and 4 Ethernet adapters. As only adapters Ethernet and Ethernet 2 are up, we can easily conclude that they are part of this team. You can always check that with the power shell commands explained in this post.

Restarting any specific network adapter

Now, we need to restart the adapter named Team1. We can perform this operation with the command Restart-NetAdapter. This command will disable and enable any specific network adapter.

Why we cannot use here commands Disable-NetAdapter and Enable-NetAdapter? We’re working through the Remote Desktop session and if we disable the network adapter used for our remote communication, we will effectively cut ourselves from that server.

I executed the command:

PS C:WINDOWSsystem32> Restart-NetAdapter -Name "Team1"
PS C:WINDOWSsystem32>

The only needed parameter is the name of the specific network adapter.

After a few seconds, the remote desktop connection was intermittent.

clip_image004

After a while, the remote desktop connection was established again.

Checking the network connection

I switched back to the Network and Internet settings GUI and checked the status of this network adapter. As I expected, it was switched into the correct domain mode.

clip_image006

As you can see, the network adapter named Team1 changed its state to domain network (the domain name contoso.com is displayed here).

When I changed this network profile, the host firewall changed to the new profile and more services became available. The Dude server successfully checked all monitored services on this server and its icon turn to green.

That was the simple trick for the great solution. Case successfully closed.

Stay tuned.

После включения своего компьютера на windows7х64 из спящего режима у меня переставал работать адаптер проводной сети. И чтобы зайти в интернет приходилось перезапускать его вручную через диспетчер устройств. Целых 11 кликов мышкой, что достаточно много секунд времени. Сегодня мне это надоело и я решил автоматизировать перезапуск адаптера.

По запросу «отключить устройство из командной строки» все прекрасно гуглится. Но я все же напишу и у себя. Ибо повозиться пришлось и подводные камни нашлись.

Для включения/отключения устройств из командной строки есть консольная программка под windows от microsoft по имени devcon (device console). Но проблема в том, что программа по указанной ссылке работает только в Windows 2000, XP и Server 2003, но не работает в windows7x64. Официальный путь это скачать отсюда WDK 8.1 Update и Visual Studio Express 2013 for Windows Desktop. Что выльется в много мегабайт. Хотя надо оттуда всего 80 КБ. У меня уже стояла Visual Studio 2010 Professional, полученная бесплатно по программе dreamspark по скану студенческого несколько лет назад. Я поставил WDK 8.1 Update и нашел заветный devcon.exe в папке C:Program Files (x86)Windows Kits8.1Toolsx64.

Но есть добрый человек, которые скачал вышеназванное и выложил отдельно devcon работающий в windows7x64, а также долженствующий работать во всех версиях windows 7, 8, 8.1. Ну а от меня держите зеркало на devconWindows7,8,8.1×86 и devconWindows7,8,8.1×64. Я скачал со своего зеркала, распаковал и закинул devcon.exe в C:WindowsSystem32. И наконец-то ее стало можно запускать в командной строке.

Для выполнения сразу нескольких команд в cmd.exe я написал *.bat файл в моём любимом текстовом редакторе notepad++. Содержимое *.bat файла у меня получилось такое:

::Отключение устройства с заданным ID
devcon disable "PCIVEN_1969&DEV_1026&SUBSYS_83041043&REV_B0"
::Включение устройства с заданным ID.
devcon enable "PCIVEN_1969&DEV_1026&SUBSYS_83041043&REV_B0"

Чтобы узнать ID я зашел в Диспетчер устройств — Свойства нужного устройства, перешел во вкладку Сведения, в выпадающем списке выбирал «ИД оборудования» и взял первую строку.

Чтобы такой *.bat файл заработал его приходится запускать от имени администратора и подтверждать свои намерения во всплывающем окне контроля учетных записей пользователя.

Но я погуглил и нашел способ запускать от имени администратора, без подтверждения, через создание задачи с наивысшим приоритетом в Планировщике заданий. Погуглил еще и понял как запускать задачу при выходе из спящего режима.

Т.е. сделал так:
Клавиша win — Планировщик заданий — меню — действие — создать простую задачу
Задал имя.
Триггер — при занесении в журнал указанного события.
Журнал: Microsoft-Windows-Diagnostics-Performance
Источник: Diagnostics-Performance
Код события: 300
Действие — запустить программу. Указал путь к *.bat файлу. И в последнем окне мастера перед нажатием кнопки Готово установил галочку для открытия окна Свойства. В открывшемся окне выбрал Выполнять с наивысшими правами и Настроить для windows 7.

И теперь при выходе из спящего режима сетевой адаптер перезапускается автоматически, интернет почти сразу есть, и я доволен.

When I log into Windows 7 I need to wait 10 seconds and then disable the Local Area Connection (ethernet adaptor) and then reenable it.

I have looked through the suggested answer: Enable/disable wireless interface in a bat file but that seems irrelevant as it just toggles the current state.

From what I can tell I need to include:

netsh interface set interface "Local Area Connection" DISABLED
netsh interface set interface "Local Area Connection" ENABLED

but I’m unsure of the wait time or how I can have this start after Windows has successfully logged in.

What’s the best approach here?

Community's user avatar

asked Dec 18, 2012 at 1:25

rlsaj's user avatar

3

Create a Windows Scheduled Task (taskschd.msc or Control PanelSystem and SecurityAdministrative ToolsTask Scheduler) with a Trigger: begin the task At log on and in the Advanced settings delay task for 30 seconds. Then add an Action to Start a program and select your .bat script.

answered Dec 19, 2012 at 22:56

David Ruhmann's user avatar

0

I hope this helps

@echo on
timeout /t 10
netsh interface set interface "Local Area Connection" DISABLED
timeout /t 10
netsh interface set interface "Local Area Connection" ENABLED

nixda's user avatar

nixda

26.5k17 gold badges107 silver badges154 bronze badges

answered Jan 8, 2013 at 12:20

alex's user avatar

alexalex

3211 gold badge2 silver badges2 bronze badges

1

The logic is:
ping public ip (google dns 8.8.8.8), if the ping fails, then goto :RESTART and restart network adapter with name «LAN», after this loop again from the start (if ping is OK, then do nothing and ping in loop to check if adapter is connected to internet)

   @echo off 

    :LOOP
    ping 8.8.8.8
    IF ERRORLEVEL 1 goto RESTART
    IF ERRORLEVEL 0 goto LOOP
    :RESTART
    netsh interface set interface "LAN" disabled
    ping -n 3 127.0.0.1
    netsh interface set interface "LAN" enabled
    ping -n 15 127.0.0.1
    goto LOOP

answered Aug 20, 2014 at 13:37

Stalingrad's user avatar

1

Thanks guys,

I am using this command to disable and enable the problematic WiFi network adapter;

> @echo on
> timeout /t 10
> netsh interface set interface "Wi-Fi" DISABLED
> timeout /t 2
> netsh interface set interface "Wi-Fi" ENABLED

Mokubai's user avatar

Mokubai

86.9k25 gold badges199 silver badges223 bronze badges

answered Aug 7, 2016 at 18:45

MNazri's user avatar

1

VERY USEFUL info here but one piece that is missing in the answers is what to enter in the «Local Area Network». I came across this answer:

«The first step is to find the name of your wireless connection. [Right click the WiFi symbol] > Open Network and Sharing Center > Change adapter settings. It is the top line of the connection info. Mine simply said Wi-Fi, but it could be Wireless Network Connection, etc.»

BTW, if it is the LAN network card, I believe you just need to look for the name for that device.

That was key to make it work for me.

answered Nov 9, 2017 at 13:19

sw.smayer97's user avatar

1

echo off
cls 
:start
echo Choice 1
echo Choice 2
set /p choice=Yes or No?
if '%Choice%'=='1' goto :choice1
if '%Choice%'=='2' goto :choice2
echo "%Choice%" is not a valid option. Please try again. 
echo
goto start
:choice1
netsh interface set interface "Ethernet" admin=Enable
goto end 
:end
pause
exit  
:choice2
netsh interface set interface "Ethernet" admin=disable
goto end 
:end
pause
exit 

Blackwood's user avatar

Blackwood

3,09311 gold badges22 silver badges32 bronze badges

answered Jan 17, 2018 at 0:49

Frank's user avatar

FrankFrank

111 bronze badge

1

Props to the kind soul who helped setup the loop. I changed it slightly as it refused to work on SP3. Below is my updated disable/enable, based on the code provided above!

@echo off

:LOOP
ping 8.8.8.8
IF ERRORLEVEL 1 goto RESTART
IF ERRORLEVEL 0 goto LOOP
:RESTART
devcon disable "PCIVEN_1317&*"
ping -n 3 127.0.0.1
devcon enable "PCIVEN_1317&*"
ping -n 15 127.0.0.1
goto LOOP

While this does require devcon to work, this is a readily available tool from Microsoft and does a much cleaner job enabling or disabling a troublesome adapter.

http://thilina.piyasundara.org/2011/06/enabledisable-lan-interface-by-command.html shows how to do this well.

answered Apr 28, 2016 at 3:54

Ryan Riggs's user avatar

Like this post? Please share to your friends:
  • Скорость перемещения указателя windows 6 11
  • Скрытые учетные записи пользователей windows 7
  • Скрипт для очистки оперативной памяти windows 10
  • Скорость перемещения мыши в windows 10
  • Скрытые устройства в диспетчере устройств windows 10 включить