Очень часто при работе по удаленке надо передернуть сетевой кабель или отключить и включить сетевой адаптер. Но раз мы не можем это сделать физически, приходится просить кого-то это сделать или изощряться такими способами. В 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 скрипт
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”!
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
8,7303 gold badges48 silver badges63 bronze badges
asked Oct 16, 2008 at 3:00
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 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 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
answered Oct 16, 2008 at 4:02
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
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
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
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
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.
- 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
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 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
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 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
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
Перезапуск сетевого адаптера скриптом в Windows, Linux
Очень часто при работе по удаленке надо передернуть сетевой кабель или отключить и включить сетевой адаптер. Но раз мы не можем это сделать физически, приходится просить кого-то это сделать или изощряться такими способами.
В Linux это происходит легко, через ssh вбиваем ifdown eth0 & ifup eth0 и всё норм.
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.
Радмир Рамазанов 25.05.2017
P.S. один раз скрипт не заработал, пришлось рано утром ехать на объект, так что применяем на свой страх и риск
зачем пинговать в данной ситуации? и почему 6 раз?
Это нужно для того, чтобы выждать паузу длительностью 6 секунд. Чтобы система успела сначала отключить, потом включить и не тупила. На почту отписался
sleep 6 – ожидание 6 секунд
не надо ping – колхозно это как-то )))
а так – хороший пост, спасибо.
спасибо за вариант.
сейчас не вспомню почему отказался, но вроде бы в XP такой команды не было, а здесь – универсальный способ.
p.s. ещё есть вариант timeout /t 6
Виктор:
28.04.2019 в 02:45
Давно этот пост помог, но со временем пришлось его доводить до ума под свои задачи, может еще кому пригодится.
Перезапуск всех активных сетевых адаптеров в системе:
for /f delims^=^”^ tokens^=2 %%a in (‘netsh interface ip show config ^| findstr “Наст conf”‘) do @(
echo. Перезапуск: %%a
netsh interface set interface name=”%%a” admin=disabled
ping -n 3 localhost>nul
netsh interface set interface name=”%%a” admin=enabled
)
Спасибо, пригодилось!
Для новичков дам подсказку – данный скрипт удобнее сохранять в Notepad++, при сохранении выбрать тип файла *.bat и в имени файла в конце прописать .bat
external help file | Module Name | ms.date | online version | schema | title |
---|---|---|---|---|---|
MSFT_NetAdapter.cmdletDefinition.cdxml-help.xml |
NetAdapter |
10/29/2017 |
https://learn.microsoft.com/powershell/module/netadapter/restart-netadapter?view=windowsserver2012r2-ps&wt.mc_id=ps-gethelp |
2.0.0 |
Restart-NetAdapter |
SYNOPSIS
Restarts a network adapter by disabling and then re-enabling the network adapter.
SYNTAX
ByName (Default)
Restart-NetAdapter [-Name] <String[]> [-IncludeHidden] [-PassThru] [-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>] [-AsJob] [-WhatIf] [-Confirm] [<CommonParameters>]
ByInstanceID
Restart-NetAdapter -InterfaceDescription <String[]> [-IncludeHidden] [-PassThru] [-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>] [-AsJob] [-WhatIf] [-Confirm] [<CommonParameters>]
InputObject (cdxml)
Restart-NetAdapter -InputObject <CimInstance[]> [-PassThru] [-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>] [-AsJob] [-WhatIf] [-Confirm] [<CommonParameters>]
DESCRIPTION
The Restart-NetAdapter cmdlet restarts a network adapter by disabling and then re-enabling the network adapter.
This may be needed for certain properties to take effect in a physical network adapter or to put the network adapter into a known state.
EXAMPLES
EXAMPLE 1
PS C:>Restart-NetAdapter -Name "Ethernet 2"
A version of the cmdlet that uses wildcard characters.
PS C:>Restart-NetAdapter -Name "E*2"
A version of the cmdlet that uses position.
PS C:>Restart-NetAdapter "Ethernet 2"
A version of the cmdlet that uses position and wildcard characters.
PS C:>Restart-NetAdapter E*2
This example restarts the network adapter named Ethernet 2.
PARAMETERS
-AsJob
ps_cimcommon_asjob
Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-CimSession
Runs the cmdlet in a remote session or on a remote computer.
Enter a computer name or a session object, such as the output of a New-CimSessionhttp://go.microsoft.com/fwlink/p/?LinkId=227967 or Get-CimSessionhttp://go.microsoft.com/fwlink/p/?LinkId=227966 cmdlet.
The default is the current session on the local computer.
Type: CimSession[] Parameter Sets: (All) Aliases: Session Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-Confirm
Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False
-IncludeHidden
Specifies both visible and hidden network adapters should be included.
By default only visible network adapters are included.
If a wildcard character is used in identifying a network adapter and this parameter has been specified, then the wildcard string is matched against both hidden and visible network adapters.
Type: SwitchParameter Parameter Sets: ByName, ByInstanceID Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-InputObject
Specifies the input to this cmdlet.
You can use this parameter, or you can pipe the input to this cmdlet.
Type: CimInstance[] Parameter Sets: InputObject (cdxml) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False
-InterfaceDescription
Specifies the network adapter interface description.
For a physical network adapter this is typically the name of the vendor of the network adapter followed by a part number and description, such as Contoso 12345 Gigabit Network Device
.
Type: String[] Parameter Sets: ByInstanceID Aliases: ifDesc Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False
-Name
Specifies the name of the network adapter.
Type: String[] Parameter Sets: ByName Aliases: ifAlias, InterfaceAlias Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False
-PassThru
Returns an object representing the item with which you are working.
By default, this cmdlet does not generate any output.
Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-ThrottleLimit
Specifies the maximum number of concurrent operations that can be established to run the cmdlet.
If this parameter is omitted or a value of 0
is entered, then Windows PowerShell® calculates an optimum throttle limit for the cmdlet based on the number of CIM cmdlets that are running on the computer.
The throttle limit applies only to the current cmdlet, not to the session or to the computer.
Type: Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
Type: SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False
CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
INPUTS
Microsoft.Management.Infrastructure.CimInstance#ROOT/StandardCimv2/MSFT_NetAdapter[]
The Microsoft.Management.Infrastructure.CimInstance
object is a wrapper class that displays Windows Management Instrumentation (WMI) objects.
The path after the pound sign (#
) provides the namespace and class name for the underlying WMI object.
OUTPUTS
Microsoft.Management.Infrastructure.CimInstance#ROOT/StandardCimv2/MSFT_NetAdapter
The Microsoft.Management.Infrastructure.CimInstance
object is a wrapper class that displays Windows Management Instrumentation (WMI) objects.
The path after the pound sign (#
) provides the namespace and class name for the underlying WMI object.
NOTES
RELATED LINKS
Disable-NetAdapter
Enable-NetAdapter
Get-NetAdapter
Rename-NetAdapter
Set-NetAdapter
external help file | Module Name | ms.date | online version | schema | title |
---|---|---|---|---|---|
MSFT_NetAdapter.cmdletDefinition.cdxml-help.xml |
NetAdapter |
10/29/2017 |
https://learn.microsoft.com/powershell/module/netadapter/restart-netadapter?view=windowsserver2012r2-ps&wt.mc_id=ps-gethelp |
2.0.0 |
Restart-NetAdapter |
SYNOPSIS
Restarts a network adapter by disabling and then re-enabling the network adapter.
SYNTAX
ByName (Default)
Restart-NetAdapter [-Name] <String[]> [-IncludeHidden] [-PassThru] [-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>] [-AsJob] [-WhatIf] [-Confirm] [<CommonParameters>]
ByInstanceID
Restart-NetAdapter -InterfaceDescription <String[]> [-IncludeHidden] [-PassThru] [-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>] [-AsJob] [-WhatIf] [-Confirm] [<CommonParameters>]
InputObject (cdxml)
Restart-NetAdapter -InputObject <CimInstance[]> [-PassThru] [-CimSession <CimSession[]>]
[-ThrottleLimit <Int32>] [-AsJob] [-WhatIf] [-Confirm] [<CommonParameters>]
DESCRIPTION
The Restart-NetAdapter cmdlet restarts a network adapter by disabling and then re-enabling the network adapter.
This may be needed for certain properties to take effect in a physical network adapter or to put the network adapter into a known state.
EXAMPLES
EXAMPLE 1
PS C:>Restart-NetAdapter -Name "Ethernet 2"
A version of the cmdlet that uses wildcard characters.
PS C:>Restart-NetAdapter -Name "E*2"
A version of the cmdlet that uses position.
PS C:>Restart-NetAdapter "Ethernet 2"
A version of the cmdlet that uses position and wildcard characters.
PS C:>Restart-NetAdapter E*2
This example restarts the network adapter named Ethernet 2.
PARAMETERS
-AsJob
ps_cimcommon_asjob
Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-CimSession
Runs the cmdlet in a remote session or on a remote computer.
Enter a computer name or a session object, such as the output of a New-CimSessionhttp://go.microsoft.com/fwlink/p/?LinkId=227967 or Get-CimSessionhttp://go.microsoft.com/fwlink/p/?LinkId=227966 cmdlet.
The default is the current session on the local computer.
Type: CimSession[] Parameter Sets: (All) Aliases: Session Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-Confirm
Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False
-IncludeHidden
Specifies both visible and hidden network adapters should be included.
By default only visible network adapters are included.
If a wildcard character is used in identifying a network adapter and this parameter has been specified, then the wildcard string is matched against both hidden and visible network adapters.
Type: SwitchParameter Parameter Sets: ByName, ByInstanceID Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-InputObject
Specifies the input to this cmdlet.
You can use this parameter, or you can pipe the input to this cmdlet.
Type: CimInstance[] Parameter Sets: InputObject (cdxml) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False
-InterfaceDescription
Specifies the network adapter interface description.
For a physical network adapter this is typically the name of the vendor of the network adapter followed by a part number and description, such as Contoso 12345 Gigabit Network Device
.
Type: String[] Parameter Sets: ByInstanceID Aliases: ifDesc Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False
-Name
Specifies the name of the network adapter.
Type: String[] Parameter Sets: ByName Aliases: ifAlias, InterfaceAlias Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False
-PassThru
Returns an object representing the item with which you are working.
By default, this cmdlet does not generate any output.
Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-ThrottleLimit
Specifies the maximum number of concurrent operations that can be established to run the cmdlet.
If this parameter is omitted or a value of 0
is entered, then Windows PowerShell® calculates an optimum throttle limit for the cmdlet based on the number of CIM cmdlets that are running on the computer.
The throttle limit applies only to the current cmdlet, not to the session or to the computer.
Type: Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
Type: SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False
CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
INPUTS
Microsoft.Management.Infrastructure.CimInstance#ROOT/StandardCimv2/MSFT_NetAdapter[]
The Microsoft.Management.Infrastructure.CimInstance
object is a wrapper class that displays Windows Management Instrumentation (WMI) objects.
The path after the pound sign (#
) provides the namespace and class name for the underlying WMI object.
OUTPUTS
Microsoft.Management.Infrastructure.CimInstance#ROOT/StandardCimv2/MSFT_NetAdapter
The Microsoft.Management.Infrastructure.CimInstance
object is a wrapper class that displays Windows Management Instrumentation (WMI) objects.
The path after the pound sign (#
) provides the namespace and class name for the underlying WMI object.
NOTES
RELATED LINKS
Disable-NetAdapter
Enable-NetAdapter
Get-NetAdapter
Rename-NetAdapter
Set-NetAdapter
- Remove From My Forums
Автоматизация включения/выключения сетевого адаптера
-
Вопрос
-
Добрый день. Вопрос следующего характера. Есть сервер под управлением Windows Server 2008R2 Standart. В нем используется 2 сетевых адаптера. Периодически с различным интервалом, один из адаптеров «отваливается» и соответственно пропадает сеть. Происходит
это после события Event 27 e1qexpress. Лечится это элементарным «Отключением/Включением» сетевого адаптера в «Диспетчере устройств». Модель адаптера Intel 82574L Gigabit Ethernet Adapter. Драйвера установлены самые свежие.Теперь к делу. Услышал что есть возможность привязать события к сценарию. и при возникновении события выполнять сценарий. Не могли бы вы мне помочь и написать этот сценарий, так как сам я в этом деле нешурупаю совсем.
-
Перемещено
27 декабря 2012 г. 12:53
(От:Windows server 2008R2/2008)
-
Перемещено
Ответы
-
Решил довольно проще, по-крайней мере поставленную задачу выполняет. В «Журнале событий» нашел событие которое сообщает о разрыве(оно же Event
27 e1qexpress) и к нему привязал выполнение bat файла со следующим кодом:netsh interface set interface name=»WAN» disable
ping -n 1 127.0.0.1
netsh interface set interface name=»WAN» enable1 и 3 строку объяснять не нужно, а 2 использована для небольшой задержки между командами.
Теперь когда адаптер отваливается в Журнале регистрируется событие, просмотрщик событий это отслеживает и запускает на выполнение мой .bat.
-
Помечено в качестве ответа
Sneginka-pasha
27 декабря 2012 г. 15:25
-
Помечено в качестве ответа
-
netsh interface ? поможет
interface name это не имя сетевой карты, а имя сетевого подключеня, которое по умолчанию именутеся, как «Подключение
по локальной сети» (local area connection)set это установка параметра(ов)
-
Помечено в качестве ответа
KazunEditor
5 сентября 2013 г. 7:22
-
Помечено в качестве ответа
Приветствую. уже не первый день бьюсь с автоматизацией, задача перезагрузка адаптера интернет по проводу.
Пытался релизовать .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, но не дало результата