Command/Powershell script to reset a network adapter - powershell

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?

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.

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.

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

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

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

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.

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);
}
}
}
}
}

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

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 PCI\VEN_16* (using the '*' wildcard to avoid needing to enter the entire ID string).

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

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

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).

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...

Related

How can I identify the network adapter (or interface) name used for a successful ping in a window bat or powershell

Is there a way to identify the network adapter (or interface) name used for a successful ping
eg I have the following adapters:
I perform the command
ping google.com
which is successful, I would like to know that the adapter used is either "Wi-Fi" Sunrise_5GHz_387918
There is a similar question for c#
Identifying active network interface
But I am looking for a windows batch file way (possibly powershell).
You can do that in PS using:
get-wmiobject win32_networkadapter | select netconnectionid, name, InterfaceIndex, netconnectionstatus
OR,
You can use netsh
netsh interface ipv4 show interfaces
In the newer version of PS like in windows 8, you can even directly use:
Get-NetAdapter | SELECT name, status, speed, fullduplex | where status -eq 'up'
Note by that the netconnectionstatus value indicates the connection status. 2 indicates connected

How to set a static IP address in windows 10?

After searching a code to set a static IP adress using a simple script, I could not find a complete and easy to implement answer on StackOverflow. That led me to the following question:
What would be an "easy^"-to-implement code to set your windows 10 IP adress to a static IP adress, and back to a dynamic IP adress again?
^ Note: Easy is meant as an indicator to ensure the code and its complete implementation is as simple as possible, not that the user could not find it challenging.
Please note that this is the implementation of: http://www.midnightdba.com/Jen/2014/03/configure-static-or-dynamic-ip-and-dns-with-powershell/. All credits go to MidnightDBA. I hope it benefits someone!
To set the IP adress to static manually
Start>control panel>Network and Internet>Network and Sharing Center>Change adapter settings>rmb on the ethernet/wifi/connection that is in use>properties>Select: Internet Protocol Version 4(TCP/IPv4)>Properties>
That should result in the screen similar to the attached image. There you can fill in the numbers manually. These numbers will (probably) be different in your own situation, you need to do the work suggested in note 3. to determine those numbers for yourself.
To set the static IP (semi-automatically):
This means you will be able to to set the IP address to static by opening a file (double clicking a script you've made), and back to a dynamic IP address by running another script you've made. The instruction steps are listed below:
start>type Powershell>rmb>Open powershell as administrator
(Only do this step if you can not immediately run the script the first time.) Type: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser and hit enter, to set the security policy so that you can run a powershell script.
create a .ps1 file named e.g. static_ip.ps1 in for example c:/example_folder with the content:
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableStatic("your_static_ip_adress", "your_subnetmask");
$wmi.SetGateways("your_routers_ip_adress", 1);
$wmi.SetDNSServerSearchOrder("your_dns");
OR to set the static IP with just a single double click on the static_ip.ps1 script:
(Note example values filled in)
# 18-07-20 Todo: add wifi network detection that automatically triggers setting a static IP and back dynamic IP.
# First ensure the script is automatically ran as administrator, else it appearently does not have the privileges to change the local IP adress:
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
# Next set it static:
$wmi.EnableStatic("192.21.89.5", "255.255.254.0");
$wmi.SetGateways("192.21.89.1", 1);
$wmi.SetDNSServerSearchOrder("192.21.89.1");
# Now close the window this has just created.
# This leaves other Powershell windows open if they were already open before you ran this script.
# Also, It yields an error with a $ sign at the start of the line.
# Source: https://stackoverflow.com/questions/14874619/powershell-exit-doesnt-really-exit
Stop-Process -Id $PID
Then in powershell enter:
cd c:/example_folder
.\static_ip.ps1
Note, if the path to the static_ip.ps1 file contains a space change the change directory-command to:
cd "c:/example_folder"
To make the IP dynamic again (semi-automatically):
Create a text file named for example dynamic_ip.ps1 located e.g. in folder c:/examplefolder with content:
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableDHCP();
$wmi.SetDNSServerSearchOrder();
OR to just change it with a single double-click on the dynamic_ip.ps1 script:
#18-07-20 Todo: add wifi network detection that automatically triggers setting a static IP and back dynamic IP.
# First ensure the script is automatically ran as administrator, else it appearently does not have the privileges to change the local IP adress:
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
# Next set it dynamic:
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableDHCP();
$wmi.SetDNSServerSearchOrder();
# Now close the window this has just created.
# This leaves other Powershell windows open if they were already open before you ran this script.
# Also, It yields an error with a $ sign at the start of the line.
# Source: https://stackoverflow.com/questions/14874619/powershell-exit-doesnt-really-exit
Stop-Process -Id $PID
In powershell:
cd c:/example_folder
.\dynamic_ip.ps1
After you have tried it out the first time in powershell succesfully, you can simply set a static IP adress by opening/running the script by opening it with powershell (In explorer, double click the file, or right mouse button (rmb)>open with powershell). But for this to work, the path to the scripts cannot contain any spaces!
Additional notes:
Do not forget to make the IP adress dynamic again if you leave your home network again, otherwise you can get a problem when you try to access the internet in other wifi/ethernet networks!
your_static_ip_adress: you can read your dynamic ip adress and routers ip adress by: start>type cmd>open command prompt>type: ipconfig, or type: ipconfig -all.* Furthermore, the rules described in the note above, generally apply.
your_routers_ip_adress see "your_static_ip_adress", usually ends with a .1
your_subnetmask see "your_static_ip_adress"
your_dns, this can be your routers ip adress, or for example googles DNS 8.8.8.8.
Rules to determine the static IP adres:
Source:
https://www.howtogeek.com/184310/ask-htg-should-i-be-setting-static-ip-addresses-on-my-router/
3.1 Do not assign an address that ends in .0 or .255 as these addresses are typically reserved for network protocols.
3.2 Do not assign an address to the very start of the IP pool, e.g. 10.0.0.1 as the start address is always reserved for the router. Even if you’ve changed the IP address of your router for security purposes, we’d still suggest against assigning a computer.
3.3 Do not assign an address outside of the total available pool of private IP addresses. This means if your router’s pool is 10.0.0.0 through 10.255.255.255 every IP you assign (keeping in mind the prior two rules) should fall within that range.
This is the (semi) automated equivalent of manually filling in the data of the first figure of this post, in order to set a static IP.
(Wifi connection issues troubleshoot) If:
you have 2 different wifi networks (A and B) to which you can both connect at the same location
where only B has the right "your_routers_ip_adress"/local gateway-adress
And you accidentally set your local IP to (the wrong) static IP whilst connect to the wrong wifi (A),
Then disconnected the wrong wifi (A) before setting the local IP adress to dynamic again,
and (as a consequence) experience wifi troubles: (keeps scanning network requirements).
Then either:
set the local IP adress to dynamic.
Reconnect to the wrong wifi network (A).
Set it back to static, and to dynamic again.
Disconnect from wifi (A).
Now you should be able to connect to both wifi networks correct again.
Or:
set the local IP adress to static.
Reconnect to the wrong wifi network (A).
Set it back to static, and to dynamic again.
Disconnect from wifi (A).
Now you should be able to connect to both wifi networks correct again.
Nice information with GUI and PowerShell.
When you assign the IP manually by the PowerShell, the DNS server IP is important. Also, it can be done via the command prompt which is useful while managing the PCs remotely. The below post has the information. Maybe you can consider adding those steps in your post.
https://tinylaptop.net/how-to-configure-setup-static-ip-on-windows-10-laptop/

Change BIOS password through powershell

I want to build a script to change and/or set up BIOS password to HP workstations.
Script i run as follows:
C:\> $computers=Get-Content -Path c:\computers.txt
C:\> foreach ($computer in $computers) {
$passChange=Get-WmiObject -computername $computer -Namespace root/hp/instrumentedBIOS -Class HP_BIOSSettingInterface
$passChange.SetBIOSSetting('Setup Password','<utf-16/>MYNEWPASSWORD','<utf-16/>')
}
Now, the following happen:
If my BIOS has no password, the script works just fine!
If my BIOS has password already, script has Return: 6. I suppose there is
a different option for changing the BIOS password?If yes, any help
is appreciated!
If i run the script for my computer, it works.
If i run the script for another computer i get the following error:
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA).
Is there a way to enable an option to enable the RPC for this feature and then disable it again?
Thank you in advance
According to HP's documentation HP Client Management Interface the WMI interface supports remote interfacing.
You need to ensure all remote computers you're attempting to connect to have the HP custom WMI Namespace.
You also need to ensure the account you're running under has administrative permissions on all of the remote computers.
You may also need to explicitly set the impersonation to 3 which is impersonate.
For more information: Connecting to WMI Remotely with PowerShell
Also ensure the firewall on the remote computers is either off or has exclusions for WMI

How to disable windows firewall for all networked machines using the command line in Windows Server 2016?

I am currently building a Hyper-V lab consisting of a DC and multiple networked VMs, using Windows Server 2016. I'd like to completely disable the windows firewall for all existing and newly created VMs.
The best way that I've found to do this so far is via Group Policy for the Domain Profile. Then set Windows Firewall: Protect all network connections to disabled. What I would like to do is to have a way of scripting this out (using Powershell if possible).
I've found that by performing the above steps in the GUI, it creates a few entries in the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Policies\Microsoft\WindowsFirewall\DomainProfile
In each of those entries, there is a property called EnableFirewall which is set to 0. So I tried creating all of this using Powershell like this:
New-Item -path "HKLM:\SOFTWARE\Policies\Microsoft" -name WindowsFirewall
New-Item -path "HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall" -name DomainProfile
New-ItemProperty -path "HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile" -name EnableFirewall -value 0 -PropertyType DWord -Force
Unfortunately it doesn't seem to be working, so there must be something else that I'm missing.
Does anybody know how to completely disable the windows firewall for all networked machines using the command line in Windows Server 2016?
Setting up the Windows-Firewall for your domain-computers through computer-startup-script is not a great solution in my opinion.
You should definetly use Group Policy for this task.
GP does exactly what I want, I would just like a way of modifying GP using Powershell. I'm building a lab from scratch, and I'm looking to script as much of it as possible rather than using the gui.
I am not completely sure, what you are trying to achive.
You have created a lab now and I think you are trying to script a complete automatic built-up for future use. Is this correct?
If yes, then my solution is maybe what you are looking for:
Create a new GPO in your lab named "Firewall-Settings" for example.
Make all of your needed FireWall-Settings to the new GPO.
In Group Policy Editor open the main-node named „Group Policy Objects“. (important) Find the newly created GPO, right-click it and select "Backup":
Save the GPO-backup to a folder. (folder must exist)
The GPO is beeing saved and named like on the screenshot below (GUID):
That's it for the preparation. Now you maybe want to script the creation of the GPO with Powershell for future use and import the backup to obtain it's settings in a new environment:
New-GPO -Name "FireWall-Settings" | New-GPLink -Target "DC=mydomain,DC=local" # distinguishedName of Target-OU
Import-GPO -Path $PathtoGPOBackup -TargetName "FireWall-Settings" -BackupGpoName "FireWall-Settings"
The Script creates a GPO in the new environment with the name "FireWall-Settings" and links it to the target-OU.
After that you import the settings of the backup-GPO. All the domain-members in scope of the GPO will get the Windows-Firewall configured automatically.
Now the process is documented and fully automatic, if this is, what you are looking for.
Kind regards
open cmd prompt with elevated mode and run this:
netsh -r ComputerName -u Username -p Password -c advfirewall set allprofiles state off
If you want to do it for all the machines. Get all the ad computers using get-adcomputer. Run a foreach loop and put the variable istead of computername.
If you have the domain admin creds, then you are good to go with this.
Hope it helps.
Depending on the profile you want to disable, specify profiles (public, domain, private) using the -Name parameter. To disable all profiles for a networked machine, where $computerName array is the hostname of your DC, PC etc:
$computerName = 'DC1, PC1, MS1'
Invoke-Command -Computername $computerName -ScriptBlock {
Set-NetFirewallProfile -Name Domain, Public, Private -Enabled False
}

Using netsh in powershell: save store location for multiple commands

I have a powershell script which is designed to modify the domain's ipsec policy by adding an ip address to a specified filterlist. The problem is that when running netsh store location=domain domain=our.domain.com in my powershell script, it doesn't remember the store location for following commands. I have tried a workaround by creating a text file which is then run from powershell as netsh -f "path\to\textfile.txt" but it doesn't seem to work. You will find the relevant script block below. Domain is set correctly, as it works when run directly in netsh.
$command = "ipsec static
set store location=domain domain=our.domain.com
add filter filterlist=$FILTERLIST
protocol=ANY srcaddr=$ip
srcmask=255.255.255.255
dstaddr=ME
description='IP address blocked'
mirrored=YES"
$($command.Trim()) | out-file $($DIR+"\netsh\temp.txt")
netsh -f $($DIR+"\netsh\temp.txt")
remove-item $($DIR+"\netsh\temp.txt")
I didn't get it to work yet, but as I'm about to do that, it would be nice to know if there are other better-engineered solutions for that. Im running PowerShell v.1.0
Use a here string #" ... "# with each line of your script being on separate lines in between. and pipe the command to netsh
#"
winhttp show proxy
winhttp show proxy
"# | netsh