Powershell Networking Guide
Powershell Networking Guide
Windows PowerShell
Scripting Guide
by Ed Wilson
Microsoft’s “The Scripting Guy”
2
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
This guide is released under the Creative Commons Attribution-NoDerivs 3.0 Unported License. The
authors encourage you to redistribute this file as widely as possible, but ask that you do not modify
the document. However, you are encouraged to submit changes to the authors directly
(http://www.concentratedtech.com/contact) so that your suggestions can be incorporated into the
master document and published in a future revision.
PowerShell.org ebooks are works-in-progress, and many are curated by members of the community.
We encourage you to check back for new editions at least twice a year, by visiting PowerShell.org.
You may also subscribe to our monthly e-mail TechLetter for notifications of updated ebook editions.
Visit PowerShell.org for more information on the newsletter.
Feedback and corrections, as well as questions about this ebook’s content, can be posted in the
PowerShell Q&A forum on PowerShell.org. Moderators will make every attempt to either address
your concern, or to engage the appropriate ebook author.
3
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
4
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
5
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
6
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Because navigating to the Start screen and typing pow each time I want to launch Windows
PowerShell is a bit cumbersome, I prefer to Pin the Windows PowerShell console (and the Windows
PowerShell ISE) to both the Start page and to the Windows desktop taskbar. This technique of
pinning shortcuts to the applications provides single click access to Windows PowerShell from
wherever I may be working.
7
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
On Windows Server 2012 (and on Windows Server 2012 R2), it is not necessary to go through the
Start screen / Search routine because an icon for the Windows PowerShell console exists by default
on the taskbar of the desktop.
NOTE: The Windows PowerShell ISE (the script editor) does not exist by default on
Windows Server 2012 and Windows Server 2012 R2. You add the Windows PowerShell ISE
as a feature.
8
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
9
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Once you launch the Windows PowerShell console with admin rights, the User Account Control
dialog box appears seeking permission to allow Windows PowerShell to make changes to the
computer. In reality, Windows PowerShell is not making changes to the computer – not yet. But using
Windows PowerShell you can certainly make changes to the computer – if you have the rights, and
this is what the dialog is prompting you for.
NOTE: It is possible to avoid this prompt by turning off User Account Control (UAC).
However, UAC is a significant security feature, and therefore I do not recommend disabling
UAC. We have fine-tuned it in Windows 7 and continuing through Windows 8.1 and greatly
reduced the number of UAC prompts (from the number that used to exist in the introduction
of UAC on Windows Vista. This is not “your grandma’s UAC”.)
Now that you are running Windows PowerShell with admin rights, you can do anything your account
has permission to do. Therefore, if you were to, for example, run the Get-Disk cmdlets, you would see
information similar to the following appear.
PS C:\> get-disk
10
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
NOTE: The Windows PowerShell Tab Completion feature is a great time saver. It not only
saves time (by reducing the need for typing) but it also helps to ensure accuracy, because
Tab Completion accurately resolves cmdlet names – it is sort of like a spell checker for
cmdlet names. For example, attempting to type a cmdlet name such as Get-
NetAdapterEncapsulatedPacketTaskOffload accurately (for me anyway) could be an exercise
in frustration. But using tab completion, I only have to type Get-Net and I hit the <TAB> key
about six times and the correctly spelled cmdlet name appears in the Windows PowerShell
console. Learning how to quickly, and efficiently use the tab completion is one of the keys to
success in using Windows PowerShell.
To find information about Windows services, use the verb Get and the noun service. To type the
cmdlet name, type the following:
Get-Servi + <TAB> + <ENTER>
NOTE: It is a Windows PowerShell convention to use singular nouns. While not universally
applied (my computer has around 50 plural nouns) it is a good place to start. So if you are
not sure if a noun (or parameter) is singular or plural, choose the singular – most of the time
you will be correct.
11
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
12
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Name : Network 10
InterfaceAlias : vEthernet (WirelessSwitch)
InterfaceIndex : 31
NetworkCategory : Public
IPv4Connectivity : Internet
IPv6Connectivity : NoTraffic
NOTE: Windows PowerShell is not case sensitive. There are a few instances where case
sensitivity is an issue (for example when using Regular Expressions) but cmdlet names,
parameters and values are not case sensitive. Windows PowerShell convention uses a
combination of upper case and lower case letters (generally at syllable breaks in long noun
names such as NetConnectionProfile) but this is not a requirement for Windows PowerShell
to interpret accurately the command. This combination of upper case and lowercase letters
are for readability. If you use Tab Expansion, Windows PowerShell automatically converts
the commands to this fashion.
13
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
NOTE: On my laptop, both the current culture and the current UI culture are the same. This
is not always the case, and at times, I have seen machines become rather confused when the
user interface is set for a localized language, and yet the computer itself was still set for US
English (this is especially problematic when using virtual machines created in other
countries. In these cases, even a simple task like typing in a password becomes very
frustrating. To fix these types of situations you can use the Set-Culture cmdlet.
14
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
15
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
If you attempt to find only update types of hotfixes by supplying the value update in the first position,
an error raises. The offending command, and associated error, appears here.
PS C:\> Get-HotFix update
Get-HotFix : Cannot find the requested hotfix on the 'localhost' computer. Verify
16
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Required? false
Position? 1
Default value All hotfixes
Accept pipeline input? false
Accept wildcard characters? False
Well, what about using the -Description parameter, you may ask? The help file tells that the –
Description parameter is a named parameter. This means you can only use the –Description
parameter if you specify the parameter name as was accomplished earlier in this section. Here is the
applicable portion of the help file for the –Description parameter.
-Description <String[]>
Gets only hotfixes with the specified descriptions. Wildcards are
permitted. The default is all hotfixes on the computer.
Required? false
Position? named
Default value All hotfixes
Accept pipeline input? false
Accept wildcard characters? True
17
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Required? false
Position? 1
Default value
Accept pipeline input? true (ByPropertyName)
Accept wildcard characters? True
NOTE: Be careful using positional parameters. This is because they can be confusing. For
example, the first parameter for the Get-Process cmdlet is the –Name parameter, but the first
position parameter for the Stop-Parameter is the –ID parameter. As a best practice always
refer to the Help files to see what the parameters actually are called, and the position in
which they are expected. This is even more important when using cmdlet with multiple
parameters – such as the Get-Random cmdlet discussed next.
18
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
The command and the output associated with the command appears here.
PS C:\> Get-Random -Maximum 21 -Minimum 1
19
Required? true
Position? 1
Default value
Accept pipeline input? true (ByValue)
Accept wildcard characters? False
An array (or a range) of numbers just happens to also be a collection of objects. The easiest way to
generate a range (or an array) of numbers is to use the range operator. The range operator is two
dots (periods) between two numbers. The range operator does not require spaces between the
numbers, and dots. This appears here.
PS C:\> 1..5
1
19
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
2
3
4
5
Now to pick five random numbers from the range of 1 to 10, only requires the command appearing
here. (The parentheses are required around the range of 1 to 10 numbers to ensure the range of
numbers creates prior to attempting to select five from the collection.
Get-Random -InputObject (1..10) -Count 5
The command and output associated with the command appear here.
PS C:\> Get-Random -InputObject (1..10) -Count 5
7
5
10
1
8
20
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
If I use the Get-Command cmdlet and an error arises, it may be because the module has not yet
loaded. To load the module use the Import-Module cmdlet. This command appears here.
Import-Module NetAdapter
21
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
If I am curious as to the number of commands exposed by the module, I can pipeline the results to the
Measure-Object cmdlet. This command appears here.
22
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
All things being equal, what tools are available to me to use to accomplish my work with network
adapters?
1. Windows PowerShell
2. NetSH
3. Windows Management Instrumentation (WMI)
4. VBScript
5. Console Utilities
In this booklet, I will talk about each of these approaches as I look at the different tasks. So what tasks
am I talking about? Well, I am specifically talking about the network adapter. So here are the things I
am going to cover:
1. Identifying network adapters
2. Enabling and disabling network adapters
3. Renaming network adapters
4. Finding connected network adapters
5. Identifying network adapter power setting
6. Configuring network adapter power settings
7. Gathering network adapter statistics
Along the way, I will be showing some pretty cool Windows PowerShell tricks.
PowerTip: Find protocol binding on net adapters using PowerShell
Question: How can you use Windows PowerShell to show which enabled protocols are
bound to your network adapters using Windows 8.1 and PowerShell 4.0?
Answer: Use the Get-Netadapter cmdlet to retrieve all of the network adapters on your
system. Then pipeline it to the Get-NetAdapterBinding cmdlet and filter on enabled is equal
to true. This command appears here:
Get-NetAdapter | Get-NetAdapterBinding | ? enabled -eq $true
23
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
The problem with this methodology nowadays is that some of the pseudo adapters are also
IPEnabled. The above command would eliminate many, but not necessarily all of the adapters.
A better approach is to look at the Win32_NetworkAdapter class and query the NetConnectionStatus
property. Using this technique, I return only network adapter devices that are actually connected to a
network. While it is possible that a pseudo adapter could sneak under the wire, the likelihood is more
remote. In this command, I will use the Get-WmiObject PowerShell cmdlet to return all instances of
Win32_NetworkAdapter class on the computer. I then create a table to display the data returned by
the NetConnectionStatus property.
Get-WmiObject -Class Win32_NetworkAdapter |
Format-Table -Property Name, NetConnectionStatus –AutoSize
The fruit of our labor is somewhat impressive. I have a nice table that details all of the fake and real
network adapters on our laptop, as well as the connection status of each. Here is the list from my
laptop.
Name NetConnectionStatus
---- -------------------
WAN Miniport (L2TP)
WAN Miniport (PPTP)
WAN Miniport (PPPOE)
WAN Miniport (IPv6)
Intel(R) PRO/1000 PL Network Connection 2
Intel(R) PRO/Wireless 3945ABG Network Connection 0
WAN Miniport (IP)
Microsoft 6to4 Adapter
24
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
25
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
7 Media disconnected
8 Authenticating
9 Authentication succeeded
10 Authentication failed
11 Invalid address
12 Credentials required
The value of 2 means the network adapter is connected. Here is the code I wrote to exploit the results
of our research.
Get-WmiObject -class win32_networkadapter -filter "NetConnectionStatus = 2" |
Format-List -Property [a-z]*
Such ecstasy is short lived; however, when I realize that while I have indeed returned information
about a network adapter that is connected, I do not have any of the configuration information from
the card.
What I need is to be able to use the NetConnectionStatus property from Win32_Networkadapter and
to be able to obtain the Tcp/Ip configuration information from the
Win32_NetworkAdapterConfiguration WMI class. This sounds like a job for an association class. In
VBScript querying an Association class involved performing confusing AssociatorsOf queries (Refer
to the MSPress book, "Window Scripting with WMI: Self Paced Learning Guide" for more information
about this technique.)
Using the association class with Windows PowerShell, I come up with the
FilterAssociatedNetworkAdapters.ps1 script shown here.
FilterAssociatedNetworkAdapters.ps1
Param($computer = "localhost")
function funline ($strIN)
{
$num = $strIN.length
for($i=1 ; $i -le $num ; $i++)
{ $funline = $funline + "=" }
Write-Host -ForegroundColor yellow $strIN
Write-Host -ForegroundColor darkYellow $funline
} #end funline
I begin the script by using a command line parameter to allow us to run the script remotely if needed.
I use the Param statement to do this. I also create a function named funline that is used to underline
the results of the query. It makes the output nicer if there is a large amount of data returned.
Param($computer = "localhost")
function funline ($strIN)
{
$num = $strIN.length
for($i=1 ; $i -le $num ; $i++)
{ $funline = $funline + "=" }
Write-Host -ForegroundColor yellow $strIN
26
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
I print out the name of the computer by using the Write-Host cmdlet as seen here. I use the color
cyan so the text will show up real nice on the screen (unless of course your background is also cyan,
then the output will be written in invisible ink. That might be cool as well.)
Write-Host -ForegroundColor cyan "Network adapter settings on $computer"
Then I get down to actual WMI query. To do this, I use the Get-WmiObject cmdlet. I use the –
computername parameter to allow the script to run against other computers, and I pipeline the
results to the ForEach-Object cmdlet.
Get-WmiObject -Class win32_NetworkAdapterSetting `
-computername $computer |
Foreach-object `
The hard part of the query is seen here. I need a way to look at the netConnectionStatus property of
the Win32_NetworkAdapter class. This class is referred to by the reference returned from the
association query. It is called element. To gain access to this class, I use the reference that was
returned and feed it to the [WMI] type accelerator (it likes to receive a path, and this is what the
reference is). Since the reference refers to a specific instance of a WMI class, and since the [WMI]
type accelerator can query a specific instance of a class, I are now able to obtain the value of the
netConenctionStatus property. So I say in our script, if it is equal to 2, then I will print out the name of
the network adapter, and the configuration that is held in the setting property and the adapter
information that held in the element property. This section of the code is seen here.
{
If( ([wmi]$_.element).netconnectionstatus -eq 2)
{
funline("Adapter: $($_.setting)")
[wmi]$_.setting
[wmi]$_.element
} #end if
The result of running the script is that it displays information from both the Win32_NetworkAdapter
WMI class and the Win32_NetworkAdapterConfiguration class. It also shows us I only have one
connected network adapter.
Using NetSh
Microsoft created NetSh back in 2000, and it has been a staple of networking ever since then. When I
open it up, now days, it displays a message saying that it might be removed in future versions of
Windows, and therefore I should begin using Windows PowerShell. Here is the message:
27
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Now, because NetSh is an old style menu type application, it is possible to enter NetSh, and walk my
way down through the menus until you arrive at the proper location. Along the way, if I get lost, I can
use the ? to obtain help. The problem, is that the help is quite often not very helpful, and therefore it
takes me at times nearly a dozen times before the command is correct. The great thing is that, for the
most part, Once I figure out a command, I can actually keep track of my location in the program, and
back all the way out and enter the command as a one linner. Here is the NetSh command to display
network interface information that is bound to Ipv4:
netsh interface ipv4 show interfaces
The output appears here:
28
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
To focus in on a particular network adapter, I use the name parameter and supply the name of the
network adapter. The good thing, is that in Windows 8 (and on Windows Server 2012) the network
connections receive new names. No more of the “local area connection” and “local area connection(2)
to attempt to demystify. The wired network adapter is simply Ethernet and the wireless network
adapter is Wi-Fi. The following command retrieves only then Ethernet network adapter.
Get-NetAdapter -Name Ethernet
To dive into the details of the Ethernet network adapter, I pipeline the returned object to the Format-
List cmdlet and I choose all of the properties. The command appearing here uses the fl alias for the
Format-List cmdlet.
Get-NetAdapter -Name ethernet | Format-List *
The command and output associated with the command appear in the figure that follows.
29
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
There are a number of excellent properties that might bear further investigation, for example there
are the adminstatus and the mediaconnectionstatus properties. The following command returns those
two properties.
Get-NetAdapter -Name ethernet | select adminstatus, MediaConnectionState
Of course, there are other properties that might be interesting as well. These properties appear here,
along with the associated output (the following is a single logical command broken on two lines).
Get-NetAdapter -Name ethernet |
select ifname, adminstatus, MediaConnectionState, LinkSpeed, PhysicalMediaType
I decide to look only for network adapters that are in the admin status of up. I use the command
appearing here.
PS C:\> Get-NetAdapter | where adminstatus -eq "up"
To find the disabled network adapters, I change the adminstatus from up to down. This command
appears here.
Get-NetAdapter | where adminstatus -eq "down"
I go back to my previous command, and modify it to return WI-FI information. This command, and
associated output appears here (this is a single logical command).
PS C:\> Get-NetAdapter -Name wi-fi |
select ifname, adminstatus, MediaConnectionState, LinkSpeed, PhysicalMediaType
ifName : WiFi_0
AdminStatus : Up
MediaConnectionState : Connected
LinkSpeed : 54 Mbps
PhysicalMediaType : Native 802.11
30
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
If I want to find any network adapters sniffing the network, I look for promiscousmode. This
command appears here.
Get-NetAdapter | ? PromiscuousMode -eq $true
When I combine the Get-NetAdapter function with the Get-NetAdapterBinding function I can easily
find out which protocols are bound to which network adapter. I just send the results to the Where-
Object and check to see if the enabled property is equal to true or not. Here is the command.
Get-NetAdapter | Get-NetAdapterBinding | ? enabled -eq $true
Here is an example of both the command and the output from the command.
If I want to find which network adapters have the Client for Microsoft Networks bound, I need to first
see which protocols are enabled (using the syntax from the previous command) and I need to see
which one of the enabled protocols have the display name of Client for Microsoft Networks. This
requires a compound where-object statement and therefore I cannot use the simplified syntax. Also,
because only one of the protocols begins with Client … I can use that to shorten my query just a bit.
Here is the command I use (this is a one line command that I broke at the pipe character to make a
better display).
Get-NetAdapter |
Get-NetAdapterBinding |
where {$_.enabled -AND $_.displayname -match 'client'}
31
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
32
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Using Devcon
In the old days, back before Windows Vista and Windows Server 2008 when I needed to enable or
disable a network adapter, I would actually use Devcon. Devcon is a command line utility that
provides the ability to enable and to disable various hardware devices. It is billed as a command-line
Device Manager. Here is a VBScript I wrote to enable and to disable the network interface adapter
using Devcon. Keep in mind that Devcon is not installed by default, and therefore must be installed
prior to use.
'==========================================================================
'
' VBScript: AUTHOR: Ed Wilson , MS, 5/5/2004
'
' NAME: <turnONoffNet.vbs>
'
' COMMENT: Key concepts are listed below:
'1.uses the c:\devcon utility to turn on or off net
'2.uses a vbyesNO msgBOX to solicit input
'3. KB 311272 talks about devcon and shows where to get
'==========================================================================
Option Explicit
Dim objShell
Dim objExec
Dim onWireLess
33
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Dim onLoopBack
Dim turnON
Dim turnOFF
Dim yesNO
Dim message, msgTitle
Dim strText
message = "Turn On Wireless? Loop is disabled" & vbcrlf & "if not, then wireless is disabled and loop
enabled"
msgTitle = "change Network settings"
onWireLess = " PCMCIA\Dell-0156-0002"
onLoopBack = " *loop"
turnON = "enable"
turnOFF = "disable"
Const yes = 6
Sub subOUT
Do until objExec.StdOut.AtEndOfStream
strText = objExec.StdOut.ReadLine()
Wscript.Echo strText
34
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Loop
End sub
Using WMI
Beginning with Windows Vista (and Windows Server 2008) the Win32_NetworkAdapter class gains
two methods: disable and enable. These are documented on MSDN here. These methods are instance
methods which means that to use them, I need to first obtain an instance of the WMI class. What does
this mean? Well I am using Win32_NetworkAdapter and therefore I am working with network
adapters. So, I need to get a specific network adapter, and then I can disable it or enable it. Here is
how it might work:
$wmi = Get-WmiObject -Class Win32_NetworkAdapter -filter "Name LIKE
'%Wireless%'"
$wmi.disable()
OR
The thing to keep in mind is that when calling a method in Windows PowerShell, the parenthesis are
required.
If I need to specify alternate credentials, I can specify a remote computer name and an account that
has local admin rights on the remote box. The code would appear like the following:
$wmi = Get-WmiObject -Class Win32_NetworkAdapter -filter "Name LIKE
'%Wireless%'" –credential (Get-Credential) –computername remotecomputer
$wmi.disable()
Keep in mind that WMI does not permit alternate credentials for a local connection. Attempts to use
alternate credentials for a local connection results in the error appearing here:
PS C:\> gwmi win32_networkadapter -Credential (Get-Credential)
This error, for local connections, is not a Windows PowerShell thing, WMI has always behaved in this
manner, even going back to the VBScript days.
35
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Name ModuleName
---- ----------
Disable-NetAdapter NetAdapter
Enable-NetAdapter NetAdapter
Get-NetAdapter NetAdapter
Rename-NetAdapter NetAdapter
Restart-NetAdapter NetAdapter
Set-NetAdapter NetAdapter
NOTE: To enable or to disable network adapters requires admin rights. Therefore you must
start the Windows PowerShell console with an account that has rights to perform the task.
The various network adapters on my laptop appear in the figure that follows.
I do not like having enabled, disconnected network adapters. Instead, I prefer to only enable the
network adapter I am using (there are a number of reasons for this such as simplified routing tables,
performance issues, and security concerns). In the past, I wrote a script, now I only need to use a
Windows PowerShell command. If I only want to disable the non-connected network adapters, the
command is easy. It appears here.
Get-NetAdapter | ? status -ne up | Disable-NetAdapter
The problem with the previous command is that it prompts. This is not much fun when there are
multiple network adapters to disable. The prompt appears here.
36
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
To suppress the prompt, I need to supply $false to the –confirm parameter. This appears here.
Get-NetAdapter | ? status -ne up | Disable-NetAdapter -Confirm:$false
A quick check in control panel shows the disconnected adapters are now disabled. This appears here.
If I want to enable a specific network adapter, I use the Enable-Network adapter. I can specify by
name as appears here.
Enable-NetAdapter -Name ethernet -Confirm:$false
If I do not want to type the adapter name, I can use the Get-NetAdapter cmdlet to retrieve a specific
network adapter and then enable it. This appears here.
Get-NetAdapter -Name vethernet* | ? status -eq disabled | Enable-NetAdapter -
Confirm:$false
37
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
It is also possible to use wild card characters with the Get-NetAdapter to retrieve multiple adapters
and pipeline them directly to the Disable-NetAdapter cmdlet. The following permits the confirmation
prompts so that I can selectively enable or disable the adapter as I wish.
PS C:\> Get-NetAdapter -Name vethernet* | Disable-NetAdapter
Confirm
Are you sure you want to perform this action?
Disable-NetAdapter 'vEthernet (InternalSwitch)'
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):y
Confirm
Are you sure you want to perform this action?
Disable-NetAdapter 'vEthernet (ExternalSwitch)'
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):n
38
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Using NetSh
To rename the network adapter using NetSh I need to know the interface name, and the new name I
want to use. This is about it. To find the network adapter names, I can also use NetSh. Here is the
command:
netsh interface ipv4 show interfaces
NetSh is available everywhere right now. So, I can use NetSh to configure network adapters from
Windows 2000 forward – so it has the greatest amount of backward compatibility. But it is
deprecated, and therefore may not always be available going forward. To rename a network interface
using NetSh, I can use a command such as the one appearing here:
NetSh interface set interface name="Ethernet" newname="RenamedAdapter"
Using WMI
Beginning with Windows Vista, it is possible to use WMI to rename the network interface. The thing
to keep in mind, is that the property that I change is NetConnectionID and not the name property.
Because this command modified the NetConnectionID property, it is a simple property assignment,
and not a method call. The Win32_NetworkAdapter WMI class is documented on MSDN and the
article shows the properties that are Read and Write. The steps to using WMI include the following:
1. Retrieve the specific instance of the network adapter
2. Assign a new value for the NetConnectionID property
3. Use the Put method to write the change back to WMI
The following code illustrates these three steps using a network adapter that is named Ethernet. The
command will rename the network adapter named Ethernet to RenamedConnection:
$wmi = Get-WmiObject -Class Win32_NetworkAdapter -Filter "NetConnectionID =
'Ethernet'"
$wmi.NetConnectionID = 'RenamedConnection'
$wmi.Put()
The following figure shows using WMI to rename the network adapter.
39
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
40
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
When I run the command, nothing appears in the output. This following figure shows the single
command (wrapping in the Windows PowerShell console) and the fact that there is not output from
the command. On my Windows 8.1 laptop, I use the Get-NetAdapter command to verify that the
adapter renamed.
The good thing is that the access denied error appears – some cmdlets do not display output, and do
not let you know that you need admin rights to obtain the information (The Get-VM cmdlet is one of
those. It returns no virtual machine information, but it does not generate an error either. This
situation is also true with the Start-VM cmdlet -- does not do anything, but does not generate an error
if you do not have rights).
So I close the Windows PowerShell console, right click on the Windows PowerShell console icon I
created on my task bar, and run Windows PowerShell as Administrator. I now run the command to
rename my network adapter with the whatif parameter to ensure it accomplishes what I want. Here
is the command I use:
41
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
That is exactly what I want to happen. I now use the up arrow, and remove the whatif. Here is the
command (no output returns from this command).
Get-NetAdapter -Name Ethernet | Rename-NetAdapter -NewName Renamed
I can modify my command just a bit, and return an instance of the renamed network adapter. To do
this, I use the –passthru parameter from the Rename-NetAdapter function. One reason to do this is to
see visual confirmation that the command completed successfully. Other reasons, would be to use the
returned object to feed into other cmdlets and to perform other actions. Here is the revised
command, showing how to use –passthru
Get-NetAdapter -Name Ethernet | Rename-NetAdapter -NewName Renamed –PassThru
The command, and associated output appear in the figure that follows.
One of the really powerful things about the Get-NetAdapter function is that I can use wildcard
characters for the name parameter. This means that if I do not want to type the entire network
adapter name, I can shorten it. It also means that if I have a similar naming pattern, I can use a
wildcard pattern to retrieve them as well. Here is an example of using a wildcard.
Get-NetAdapter -Name Ether*
This command works the same as the other commands, and therefore I can pipeline the results to the
Rename-NetAdapter function. This technique appears here:
42
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
43
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Using NetSh
It is pretty easy to use NetSh to retrieve information about the connection status of network
adapters. To do so, I use the following command:
netsh interface ipv4 show interfaces
One of the problems, from a management perspective, is that the command returns text. Therefore, if
I need to parse the text to pull out specific information, such as the Interface Index number, or the
Name of the adapter, then I am going to have to resort to writing a complicated regular expression
pattern. If all I need to do is to obtain the information because I am writing to a log file as text, then
the command works great, and is the lowest common denominator – I can use it all the way back to
Windows 2000 days.
I can even run the netsh commands from within the Windows PowerShell console. This appears in
the figure that follows.
Using WMI
It is possible to use WMI and the Win32_NetworkAdapter WMI class to retrieve information about
the connection status. The NetConnectionStatus property reports backed in a coded value that
reports the status. These values are documented on MSDN for the Win32_NetworkAdapter class.
Using the Get-WmiObject Windows PowerShell cmdlet, I can work with any operating system that
installs Windows PowerShell. This includes Windows XP, Windows Server 2003 and above. The
following command returns information similar to the NetSh command.
get-wmiobject win32_networkadapter | select netconnectionid, name,
InterfaceIndex, netconnectionstatus
44
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
The command and the output from the command appear in the figure that follows.
The difference is that instead of plain text, the command returns objects that can be further
manipulated. Therefore, while the above command actually returns the network connection status of
all network adapters, the NetSh command only returns the ones that are connected. If I filter on a
netconnectionstatus of 2 I can return only the connected network adapters. The command becomes
this one (this is a single line command that I broke at the pipeline character for readability):
get-wmiobject win32_networkadapter -filter "netconnectionstatus = 2" |
select netconnectionid, name, InterfaceIndex, netconnectionstatus
45
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
If the desire is to obtain the connection status of more than just network adapters that are connected,
then the task will require writing a script to do a lookup. The lookup values appear in the table that
follows:
Value Meaning
0 Disconnected
1 Connecting
2 Connected
3 Disconnecting
4 Hardware not present
5 Hardware disabled
6 Hardware malfunction
7 Media disconnected
8 Authenticating
9 Authentication succeeded
10 Authentication failed
11 Invalid Address
12 Credentials required
The Get-NetworkAdapterStatus.ps1 script requires at least Windows PowerShell 2.0 which means
that it will run on Windows XP SP3 and above.
Get-NetworkAdapterStatus.Ps1
<#
.Synopsis
Produces a listing of network adapters and status on a local or remote
machine.
.Description
This script produces a listing of network adapters and status on a local or
remote machine.
.Example
Get-NetworkAdapterStatus.ps1 -computer MunichServer
Lists all the network adapters and status on a computer named MunichServer
.Example
Get-NetworkAdapterStatus.ps1
Lists all the network adapters and status on local computer
.Inputs
[string]
.OutPuts
[string]
.Notes
NAME: Get-NetworkAdapterStatus.ps1
AUTHOR: Ed Wilson
LASTEDIT: 1/10/2014
KEYWORDS: Hardware, Network Adapter
.Link
Http://www.ScriptingGuys.com
#Requires -Version 2.0
#>
Param(
[string]$computer= $env:COMPUTERNAME
) #end param
function Get-StatusFromValue
46
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
{
Param($SV)
switch($SV)
{
0 { " Disconnected" }
1 { " Connecting" }
2 { " Connected" }
3 { " Disconnecting" }
4 { " Hardware not present" }
5 { " Hardware disabled" }
6 { " Hardware malfunction" }
7 { " Media disconnected" }
8 { " Authenticating" }
9 { " Authentication succeeded" }
10 { " Authentication failed" }
11 { " Invalid Address" }
12 { " Credentials Required" }
Default { "Not connected" }
}
} #end Get-StatusFromValue function
If my environment is Windows 7 and Windows Server 2008 R2, I can use either Windows PowerShell
3.0 or Windows PowerShell 4.0. The advantage here, is that I gain access to the Get-CimInstance
cmdlet which uses WinRM for remoting instead of DCOM that the Get-WmiObject cmdlet uses. The
only change to the Get-NetworkAdapterStatus.ps1 script that is required is to replace the Get-
WmiObject line with Get-CimInstance. The revision appears here:
# *** Entry point to script ***
When I run the Get-StatusFromValue.ps1 script, in the Windows PowerShell ISE, I see the output
achieved here.
47
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
48
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
I can reduce the output to only physical adapters by using the –physical parameter. This command
appears here.
Get-NetAdapter –Physical
If I only want to see the physical network adapters that are actually up, I pipeline the results to the
where-object. This command appears here.
Get-NetAdapter -physical | where status -eq 'up'
The commands and the output from the two previous commands appear in the figure that follows.
49
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
50
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Question: You want to get the network adapter power management settings on your
Window 8.1 computer. How can you use Windows PowerShell to do this?
Answer: Use the Get-NetAdapterPowerManagement function and specify the name of the
network adapter to query.
Using NetSh
Some of the network adapter power management settings are configurable via NetSh. For example,
to permit ARP packets and NS packets to wake the network adapter, I would use a command such as
the following:
netsh interface ipv4 set interface 12 forcearpndwolpattern=enabled
When the command completes successfully, it returns OK. Keep in mind, this will also cause a
network adapter reset. The command and associated output appear here:
The command, and the output associated with the command appear in the figure that follows.
51
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
The Get-NetAdapterPowerManagement function only permits the use of the adapter name or
interface description as parameters. But the Get-NetAdapter function is much more flexible. I often
use Get-NetAdapter to retrieve a specific network adapter and then pipeline it to other functions
such as Get-NetAdapterPowerManagement. This technique appears here:
Get-NetAdapter -InterfaceIndex 4 | Get-NetAdapterPowerManagement
Because no output returns from the command, I use the Get-NetAdapter command a second time to
verify the configuration change took place. The commands and associated output appear in the figure
that follows.
Now, it so happens that I know what the permissible values are for the parameters. But if I did not
know this, I could create the command in the Windows PowerShell ISE and rely upon the intellisense
features. When I type a parameter name, the permissible values appear and make it possible to select
the correct value from the list. This appears in the figure that follows.
52
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Most of the times, when I need to manage network adapter power management settings, it is because
of a new deployment, or because an audit has determined that I have configuration drift. (Hmmm …
this would actually be a great thing to use Desired Configuration Management to control.) So, what I
do is put all the settings I want to configure into a single command. Such a command appears here:
Set-NetAdapterPowerManagement -Name ethernet -ArpOffload Enabled -DeviceSleep
OnDisconnect Disabled -NSOffload Enabled -WakeOnMagicPacket Enabled -
WakeOnPattern En
abled -PassThru
The –passthru parameter outputs a configuration management object so that I can inspect it and
ensure that the proper things change that I wanted changed. The command, and the output from the
command appear in the figure that follows:
To make changes to multiple computers, I first use the New-CimSession cmdlet to make my remote
connections. I can specify the computer names and the credentials to use to make the connection. I
then store the remote connection in a variable. Next, I pass that cimsession to the –cimsession
parameter. The key to remember here, is that I must be able to identify the network adapter that I
need to use for the management activity. An example of creating a Cim Session and using it appears
here (keep in mind this is a two line command. If you directly copy and paste this command you must
53
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
change the computer name, network interface name, and remove spaces until the second command
appears on a single line).
$session = New-CimSession -ComputerName edlt
Set-NetAdapterPowerManagement -CimSession $session -name ethernet -ArpOffload
Enabled -DeviceSleepOnDisconnect Disabled -NSOffload Enabled -WakeOnMagicPacket
Enabled -WakeOnPattern Enabled -PassThru
The command and the output from the command appear in the figure that follows.
Keep in mind that these commands require that either the Windows PowerShell console or the
Windows PowerShell ISE is opened with admin rights. To do this, right click on the Windows
PowerShell console icon or Windows PowerShell ISE icon while holding down the shift key and select
run as administrator. Or if you launch it via Windows Search on Windows 8.1 type Windows
PowerShell from the Start page, and the Search dialog appears with the Windows PowerShell icon.
Right click on the icon and select Run as Administrator from the action menu.
If you do not launch Windows PowerShell with admin rights, an error occurs stating that it cannot
find the network adapter. An example of the error appears in the figure that follows.
54
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
NetSh
Using NetSh to obtain network statistics is easy and powerful. For example to show IP statistics, I use
the command appearing here.
netsh interface ipv4 show ipstats
A sample output from this command appears in the figure that follows.
To show TCP statistics using NetSh, I use the command appearing here.
netsh interface ipv4 show tcpstats
55
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
The command, and the output from the command appear in the figure that follows.
One of the cool things about using NetSh from within Windows PowerShell is that I have the power of
Windows PowerShell at my fingertips. Rather than keep going back and forth to find stuff, I can
pipeline the results from a command to the Select-String cmdlet. For example, if I am interested in
how many commands are available to show statistics, I use the command appearing here because I
noticed that each of the commands contains the letters stats:
netsh interface ipv4 show | Select-String "stats"
The output from the command appears here:
PS C:\> netsh interface ipv4 show | Select-String "stats"
show icmpstats - Displays ICMP statistics.
show ipstats - Displays IP statistics.
show tcpstats - Displays TCP statistics.
show udpstats - Displays UDP statistics.
In addition to the IPV4 interface, I can also work with the IPV6 interface and obtain similar statistics.
Here is the command I used to obtain that information:
PS C:\> netsh interface ipv6 show | Select-String "stats"
56
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
In addition to using the Select-String cmdlet to parse the output from the NetSh help, I can also use it
to hone in on specific information from the statistics. For example, the following command retrieves
IPv6 interface IP stats.
netsh interface ipv6 show ipstats
I can hone in on the output and look for errors by piplining the results to the Select-String cmdlet and
choosing error. This command appears here.
netsh interface ipv6 show ipstats | Select-String errors
In the figure that follows, I first show the command to retrieve the IPV6 IP statistics. Next I show the
output from the command. Then I filter the output to only errors by using the Select-String cmdlet
and lastly, I show the output from the filtered string.
NetStat
The NetStat command has been around in the Windows world for a long time. It provides a quick
snapshot of connections from local ports to remote ports as well as the protocol and the state of
those connections. It takes a couple of minutes to run, and as a result it makes sense to store the
results of NetStat into a variable. I can then examine the information several times if I wish without
having to wait each time to gather the information additional times. Here is an example of running
the NetStat command and storing the results from in a variable.
$net = NetStat
57
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
To display the information in an unfiltered fashion, I just type $net at the Windows PowerShell
prompt and it displays all of the information that it gathered. Here is an example:
$net
The command to run NetStat and store the results in a variable as well as to examine the contents of
the $net variable appear in the figure that follows.
The real power, however, comes in using Windows PowerShell to parse the text output to find
specific information. For example, the previous output shows multiple connections in various states
of connectiveness. I can easily parse the output and find only the connections that are Established.
The command I use appears here.
$net | select-string "Established"
The command and the output from the command appear in the figure that follows.
58
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Interestingly enough, I can also use NetSh to report on TCP connections. The command appears here:
netsh interface ipv4 show tcpconnections
The output from the command, as appears in the figure that follows, is a bit different than that
received from NetStat.
59
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Performance Counters
To collect performance counter information, I need to know the performance counter set names so I
can easily gather the information. To do this, I use the Get-Counter cmdlet and I choose all of the
listsets. I then like to sort on the countersetName property and then select only that property. The
following command retrieves the available listsets.
Get-Counter -ListSet * |
Sort-Object CounterSetName |
Select-Object CounterSetName
If I pipeline the output to the Out-GridView cmdlet, then I can easily filter the list to find the listsets I
wish to use. This command appears here.
Get-Counter -ListSet * |
Sort-Object CounterSetName |
Select-Object CounterSetName |
Out-GridView
The resulting Out-GridView pane makes it easy to filter for different values. For example, the figure
that follows filters for IP.
60
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Once I have the countersetname value I wish to query, it is a simple matter of plugging it into the Get-
Counter to first obtain the paths. This command appears here.
$paths = (Get-Counter -ListSet ipv4).paths
Next I use the paths with the Get-Counter cmdlet to retrieve a single instance of the IPv4
performance information. The command appears here.
Get-Counter -Counter $paths
The commands and the output from the commands appear in the figure that follows.
61
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
If I want to monitor a counter set for a period of time, I use the –SampleInterval property and the –
MaxSamples parameter. In this way I can specify how long I want the counter collection to run. An
example of this technique appears here.
Get-Counter -Counter $paths -SampleInterval 60 -MaxSamples 60
If I want to monitor continuously, until I type Ctrl-C and break the command, I use the –Continuous
parameter and the –SampleInterval parameter. An example of this command appears here.
Get-Counter -Counter $paths -SampleInterval 30 -Continuous
The command and a sample output appear in the figure that follows.
62
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
If I want to work with a specific network adapter I can use the name of the adapter, or for more
flexibility I can pipeline the results from the Get-Netadapter function. This technique appears here.
Get-NetAdapter -ifIndex 12 | Get-NetAdapterStatistics
The Get-NetAdapterStatistics function returns more than just bytes sent and received. To find the
additional information I like to pipeline the results to the Format-List cmdlet. An example of this
technique appears here.
Get-NetAdapter -ifIndex 12 | Get-NetAdapterStatistics | format-list *
The command, and the output associated with the command appear in the figure that follows.
63
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
64
Windows PowerShell Networking Guide
by Microsoft’s “The Scripting Guy,” Ed Wilson
Resources
Books from Microsoft Press
Windows PowerShell 3.0 First Steps – A Windows PowerShell primer providing an overview of the
major Windows PowerShell components.
Windows PowerShell 3.0 Step by Step – A Windows PowerShell step by step learning guide, complete
with lab exercises, review questions, and answers. This book contains hundreds of Windows
PowerShell scripts.
Windows PowerShell Best Practices – The Windows PowerShell best practices guide, containing real
world tips, gotchas, and techniques from hundreds of field personnel. The contributors include
Microsoft Windows PowerShell developers, Microsoft Windows PowerShell MVP’s, Enterprise
network administrators, and top Dev-ops.
Web Resources
The Microsoft Script Center – dedicated to system administrator scripters the world over.
The Scripting Guys Forum – community forum for asking scripting questions.
The Script Center Script Repository – the largest collection of admin scripts on the internet.
The Hey Scripting Guy Blog – thousands of blog articles about scripting. Updated twice a day, 365
days a year, it is the #1 blog on MSDN and on TechNet.
The Script Center Community Page – insight into Windows PowerShell community activities,
especially activities where the Microsoft Scripting Guy and the Scripting Wife will appear.
The Script Center Learn PowerShell Page – central hub for learning about Windows PowerShell.
NetAdapter module documentation – official Microsoft documentation for the NetAdapter module
from TechNet.
PoshCode – Windows PowerShell community driven script repository.
PowerShell.Org – Windows PowerShell community site containing blogs, forums, user group
information and a script repository.
PowerShellSaturday.Org – listing of Windows PowerShell Saturday community events.
65