How to set a static IP address in windows 10? - powershell

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/

Related

Bulk IP configuration using CSV input

I have a CSV file with the following values for each machine I want to remotely reconfigure using static IP
name,nic,ip,mask,defaultgw
I was hoping to be able to reconfigure the IPs for each listed but if I have more than one machine listed the script gets stuck. This is because at the end of the first loop iteration, unless I manually do an ipconfig /flushdns on the server the script is running from, I will lose connection to the server being configured and the script just hangs leaving the rest of the servers. What I have so far is this:
$csv = import-csv "c:\scripts\builds\machines.csv"
foreach ($Row in $csv) {
$machine = $Row.name
$Nic = $row.Nic
$address = $row.IP
$mask =$row.mask
$defaultgw = $row.gw
invoke-command -computername $machine -scriptblock { Get-NetIpAddress - InterfaceAlias $using:nic | New-NetIPAddress -ipaddress $using:address -PrefixLength $using:mask -DefaultGateway $using:defaultgw | Register-DnsClient}}
}
Can this be done using workflows or just simple start-job?
I suspect you're losing the connection to the remote machine once you change the IP address, while the local machine hangs trying to keep the connection.
Try making the call, and dropping off a payload, then running it after you disconnect.
That is, upload the code, then spawn it, then disconnect before it has a chance to run (add a sleep to the remote code maybe?). This way, you can launch your payload and disconnect before it affects you.
For example, you could copy a file to that machine with the values it needs, then schedule a task to run in 5 seconds in the future, then disconnect before it runs. The task will then run, and since you're already disconnected, you won't be affected by it.
You might also consider DHCP with static reservations. It's far easier to manage than what you're trying to do here.

Possible to use PowerShell's Get-AppvClientPackage to list AppV packages on a machine other than my own?

I can use Get-AppvClientPackage -all [| select name] or Get-WmiObject -Namespace root\appv -Class AppvClientPackage [|select name] to list all installed AppV packages installed on my own machine. It doesn't appear to be possible to use this cmdlet to get the AppV packages installed on another machine, without remote execution.
I am asking this question in hopes of finding something that works (see purpose) or get a definitive answer that it's not possible. There may be better options available (other than PS), but my question is simply if it is possible or not, so that if the latter is the case, we can push to develop a script (which could be run by someone with elevated privileges) to gather information needed.
Purpose: Our team doesn't have visibility into SCCM (that's another option is to have that team report on what is installed where, though sometimes we need answers quickly) and remote PS execution is restricted to one security team (which is understandable), but at times (for support or decommission purposes) we need to check to see if a specific client machine has a package installed, check what AppV packages a specific client has installed, as well as check to see which machines have a particular package installed.
If there is another module or cmdlet (or even something other than powershell or WMI) that might be able to yield the same information, suggestions are welcome.
Get-WmiObject utilizes RPC to connect to remote PCs and does not require PSRemoting. In this effort, all you need to do is add the -ComputerName parameter.
#Requires -Version 3
$Target = 'localhost'
$Params=#{
Namespace = 'root\appv'
Class = 'AppvClientPackage'
Property = 'Name'
ComputerName = $Target
}
Get-WmiObject #Params
PS C:\> Get-Help -Name 'Get-WmiObject' -Parameter 'ComputerName'
-ComputerName <String[]>
Specifies the target computer for the management operation. Enter a fully
qualified domain name (FQDN), a NetBIOS name, or an IP address. When the remote
computer is in a different domain than the local computer, the fully qualified
domain name is required.
The default is the local computer. To specify the local computer, such as in a
list of computer names, use "localhost", the local computer name, or a dot (.).
This parameter does not rely on Windows PowerShell remoting, which uses
WS-Management. You can use the ComputerName parameter of Get-WmiObject even if
your computer is not configured to run WS-Management remote commands.
Required? false
Position? named
Default value None
Accept pipeline input? False
Accept wildcard characters? false

How do I completely wipe out NIC settings with Powershell?

Have a smidge of a problem. I am trying to completely blank out the IP address, subnet mask, and default gateway of a single NIC on one of my VMs.
I open up IPv4 Properties on that NIC and set it to DHCP (there is no DHCP server available to it and it isn't getting a Windows APIPA address) and then I look in Advanced and make sure there aren't alternate addresses assigned. I close out all of the windows. Then, I open up CMD and type ipconfig and it shows that it has an IP address, subnet mask, and a default gateway. I even tried Disabling and Enabling the NIC and typing Restart-NetAdapter -Name "Ethernet" and there are no changes.
In PS, I type Get-NetAdapterAdvancedProperty -DisplayName "Network Address" and it shows -- under the DisplayValue.
For some reason, and I'm not sure why (I didn't give it the ol' College Try), but when I type Set-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "0.0.0.0" it shows red. I try putting in a valid address to see if maybe the cmdlet won't take all zeros and it does the same thing. I checked the man page and I'm fairly sure that the format is correct (I tried $ip = #("0.0.0.0") and gave it $ip and $ip[0] but it still, no joy).
I just want all of the NIC settings wiped and it seems like it is but ipconfig and Get-NetIPAddress, and Get-NetIPConfiguration keep showing addresses whereas Get-NetAdapterAdvancedProperty -DisplayName "Network Address" show that it's blank.
Why won't it let me wipe the configs (without doing an OOBE SysPrep)? I feel like the answer is probably something simple that I'm just overlooking but I haven't really found anything online--it's mostly just ways to work with your NIC configurations within Powershell.
Could anyone help shine some light on what is actually going on?
Thanks.
If you have several NICs, Get-NetAdapter will list all adapters with their respective index, Get-NetAdapter -ifIndex $ | Get-NetIPAddress | Remove-NetIPAddress (substitute $ with desired adapter index) will wipe IP configuration.
In case of a vm with a single adapter you can omit the index:
Get-NetAdapter | Get-NetIPAddress | Remove-NetIPAddress

Post login script pointing to new dhcp server

I have been trying to create a post login script that will change the default gateway to a specific IP and then renews its IP but haven't had any luck. I know the normal cmd line is ipconfig \renew for renewing it IP. Any help would be appreciated.
Thanks
EDIT: I edited the old answer out as the changing dhcp to default gateway essentially makes it a new question.
Since you tagged powershell, the powershell way to do this is basically change this using WMI.
We can create the following function to do this:
function Set-IPAddress {
param( [string]$networkinterface,
[string]$gateway
)
$index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
$NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}
$NetInterface.SetGateways($gateway)
}
*I haven't explicitly tested this function.
Basically what we do, is get the number of our network adapter (index) based on it's name (networkinterface). Then we get the AdapterConfiguration object associated with that interface, and then Set the Gateway to the new gateway, which is the second function parameter.
The other way to do it in batch would be to call the netsh program. I think what you're looking for is along these lines.
netsh interface ip delete address "local area connection" gateway=all
netsh interface ip add address "local area connection" gateway=100.1.1.5 gwmetric=2
* Again, I haven't tested this.

Command/Powershell script to reset a network adapter

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