Windows Powershell Networking Guide PDF
Windows Powershell Networking Guide PDF
Table of Contents
ReadMe 0
About this Book 1
Introduction 2
Security Issues 3
Using PowerShell Cmdlets 4
Supplying Options for Cmdlets 5
Using Command-Line Utilities 6
Working with Help Options 7
Working with Modules 8
Working with Network Adapters 9
Identifying Adapters 10
Enabling and Disabling Adapters 11
Renaming Adapters 12
Finding Connected Adapters 13
Adapter Power Settings 14
Getting Network Statistics 15
Resources 16
2
Windows PowerShell Networking Guide
Created by Microsoft's "The Scripting Guy," Ed Wilson, this guide helps you understand how
PowerShell can be used to manage the networking aspects of your server and client
computers.
ReadMe 3
Windows PowerShell Networking Guide
Created by Microsoft's "The Scripting Guy," Ed Wilson, this guide helps you understand how
PowerShell can be used to manage the networking aspects of your server and client
computers.
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.
Was this book helpful? The author(s) kindly ask(s) that you make a tax-deductible (in the
US; check your laws if you live elsewhere) donation of any amount to The DevOps
Collective to support their ongoing work.
Check for Updates! Our ebooks are often updated with new and corrected content. We
make them available in three ways:
Our main, authoritative GitHub organization, with a repo for each book. Visit
https://github.com/devops-collective-inc/
Our GitBook page, where you can browse books online, or download as PDF, EPUB, or
MOBI. Using the online reader, you can link to specific chapters. Visit
https://www.gitbook.com/@devopscollective
On LeanPub, where you can download as PDF, EPUB, or MOBI (login required), and
"purchase" the books to make a donation to DevOps Collective. You can also choose to
be notified of updates. Visit https://leanpub.com/u/devopscollective
GitBook and LeanPub have slightly different PDF formatting output, so you can choose the
one you prefer. LeanPub can also notify you when we push updates. Our main GitHub repo
is authoritative; repositories on other sites are usually just mirrors used for the publishing
process. GitBook will usually contain our latest version, including not-yet-finished bits;
LeanPub always contains the most recent "public release" of any book.
There is also the Windows PowerShell ISE. The Windows PowerShell ISE is an Integrated
Scripting Environment, but this does not mean you must use it to write scripts. In fact, many
Windows PowerShell users like to write their code in the Windows PowerShell ISE to take
advantage of the color syntax-highlighting, drop down lists, and automatic parameter
revelation features. In addition, the Windows PowerShell ISE has a feature, called the
_Show Command Add-On _that permits using a mouse to create Windows PowerShell
commands from a graphical environment. Once created, the command either runs directly,
or adds to the script pane (the choice is up to you).
Introduction 5
Windows PowerShell Networking Guide
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.
Introduction 6
Windows PowerShell Networking Guide
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.
Introduction 7
Windows PowerShell Networking Guide
Even if you are an administrator on the local Windows 8 (or Windows 7) desktop machine
and you do not launch Windows PowerShell with admin rights, you will get errors when
attempting to do things like see the configuration of your disk drives. This command and
associated error appears here.
PS C:\> get-disk
get-disk : Access to a CIM resource was not available to the client.
At line:1 char:1
+ get-disk
+ ~~~~~~~~
+ CategoryInfo : PermissionDenied: (MSFT\_Disk:ROOT/Microsoft/Windows/S
torage/MSFT\_Disk) [Get-Disk], CimException
+ FullyQualifiedErrorId : MI RESULT 2,Get-Disk
TIP : There is an inconsistency with errors arising when attempting to run cmdlets that
require elevated rights. For example, when inside a non-elevated Windows PowerShell
console, the error from Get-Disk is _Access to a CIM resource was not available to the
client. _The error from Stop-Service is _Cannot open xxx service on computer. _While the
Get-VM cmdlets simply returns no information (an no error). Therefore, as a first step in
troubleshooting, check for console rights.
Security Issues 8
Windows PowerShell Networking Guide
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.
Security Issues 9
Windows PowerShell Networking Guide
PS C:\> get-disk
Security Issues 10
Windows PowerShell Networking Guide
Out of nearly 2,000 cmdlets (and functions) on Windows 8, over 25 percent of them use the
verb Get. The verb Get retrieves information. The Noun portion of the cmdlet specifies the
information retrieved. To obtain information about the processes on your system, open the
Windows PowerShell console by either clicking on the Windows PowerShell icon on the task
bar (or typing PowerShell on the start screen of Windows 8 to bring up the search results for
Windows PowerShell (as illustrated earlier)). Once the Windows PowerShell console
appears, run the Get-Process cmdlet. To do this, use the Windows PowerShell Tab
Completion feature to complete the cmdlet name. One the cmdlet name appears, press the
key to cause the command to execute.
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 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 use the Windows PowerShell Tab Completion feature to enter the Get-Process cmdlet
name onto the Windows PowerShell console command line, type the following on the first
line of the Windows PowerShell console:
The Get-Process command and the associated output from the cmdlet appear in the figure
that follows.
To find information about Windows services, use the verb Get and the noun service. To type
the cmdlet name, type the following:
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.
The command, and the output associated with the command appear here.
NOTE : The efficiency of Tab Expansion depends upon the number of cmdlets, functions, or
modules installed on the computer. As more commands become available, the efficiency of
Tab Expansion reduces correspondingly.
PS C:\> Get-Service
PS C:\> Get-NetAdapter
PS C:\> Get-NetConnectionProfile
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.
When the command runs basic information such as the Language Code ID number (LCID),
the name of the culture settings, as well as the display name of the culture settings return to
the Windows PowerShell console. The command and associated output appears here.
PS C:\> Get-Culture
The second culture related grouping of information is the current user interface (UI) settings
for Windows. The UI culture settings determine which text strings appear in user interface
elements such as menus and error messages. To determine the current UI culture settings
that are active use the Get-UICulture cmdlet. Using Tab Expansion to call the Get-UICulture
cmdlet, type the following:
The command and output associated from the command appears here.
PS C:\> Get-UICulture
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.
The above command syntax is just the same number of letters to type as doing the
following:
Get-Date + <ENTER>
The following illustrates the command and the output associated with the command.
PS C:\> Get-Date
Needless to say, I did not create all that many random numbers. I mean, who wants to do all
that typing. But once I had the Get-Random cmdlet, I actually began using random numbers
for all sorts of things. Some of the things I have used the Get-Random cmdlet to do appear
in the following list.
To wait a random amount of time prior to starting or stopping processes and services
(great for performance testing)
The Get-Random cmdlet has turned out to be one of the more useful cmdlets. To generate a
random number in the Windows PowerShell console using Tab Expansion type the following
on the first line in the console:
Get-R +<TAB>+<ENTER>
The command, and output associated with the command appears here.
PS C:\> Get-Random
248797593
The completed command and the output associated with the command appear in the figure
that follows.
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.
The error, while not really clear, seems to indicate that the Get-HotFix cmdlet attempts to
find a hotfix named _update. _This is, in fact, the attempted behavior. The help file
information for the Get-HotFix cmdlet reveals that -ID is position 1. This appears here.
-Id <String[]>
Gets only hotfixes with the specified hotfix IDs. The default is all
hotfixes on the computer.
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
You can tell that the Get-Process cmdlet accepts the -Name parameter in a positional
manner because the Help file states it is in position 1. This appears here.
-Name <String[]>
Specifies one or more processes by process name. You can type multiple
process names (separated by commas) and use wildcard characters. The
parameter name ("Name") is optional.
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.
NOTE : When using the -Maximum parameter for the Get-Random cmdlet keep in mind that
the maximum number never appears. Therefore, if you have 15 people attending your
Windows PowerShell user group meeting, you would want to set the -Maximum parameter
to 16 (unless you do not like the 15 person and do not want them to win any prizes).
The default parameter for the Get-Random cmdlet is the -Maximum parameter. This means
that you can use the Get-Random cmdlet to generate a random number in the range of 0 to
20 by using Tab Expansion on the first line of the Windows PowerShell console. Type the
following (remember Get-Random never reaches the maximum number, therefore always
use a number 1 greater than the desired upper number):
If you want to generate a random number between 1 and 20, you might think you could use
Get-Random 1 21, but that generates an error. The command and the error appear here.
PS C:\> Get-Random 1 21
Get-Random : A positional parameter cannot be found that accepts argument '21'.
At line:1 char:1
+ Get-Random 1 21
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Random], ParameterBindingEx
ception
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Comm
ands.GetRandomCommand
The error states that a positional parameter cannot be found that accepts argument '21'.
This is because the Get-Random only has one positional parameter - the -Maximum
parameter. The -Minimum parameter is a named parameter (this appears in the Help file for
the Get-Random cmdlet. Use of the Help files appears in Chapter two).
To generate a random number in the range of 1 to 20, use named parameters. To assist in
creating the command use Tab Expansion for the cmdlet name as well as for the parameter
names. Type the following to create the command using Tab Expansion.
The command and the output associated with the command appears here.
This is where command sets come into play. The -Minimum and the -Maximum parameters
specify the range within which to pick a single random number. To generate more than one
random number use the -Count parameter. Here are the two parameter sets.
The first parameter set accepts -Maximum, -Minimum and -SetSeed. The second parameter
set accepts -InputObject, -Count and -SetSeed. Therefore you cannot use -Count with -
Minimum or -Maximum - they are in two different groups of parameters (called parameter
sets).
NOTE : It is quite common for Windows PowerShell cmdlets to have multiple parameter
sets. Tab Expansion only offers parameters from one parameter set - therefore when you
choose a parameter (such as -Count from Get-Random) the non-compatable parameters do
not appear in tab Expansion. This feature keeps you from creating invalid commands. For an
overview of a cmdlets parameter sets, use the Get-Help cmdlet.
-InputObject <Object[]>
Specifies a collection of objects. Get-Random gets randomly selected
objects in random order from the collection. Enter the objects, a variabl
that contains the objects, or a command or expression that gets the
objects. You can also pipe a collection of objects to Get-Random.
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
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.
The command and output associated with the command appear here.
PS C:\> ipconfig
Windows IP Configuration
<OUTPUT TRUNCATED>
To obtain the same information using Windows PowerShell would require a more complex
command. The command to obtain IP information is Get-NetIPAddress, But there are
several advantages. For one thing, the output from the _IpConfig.exe _command is text,
whereas the output from Windows PowerShell is an object. This means you can group, sort,
filter, and format the output in an easy fashion.
The cool thing is that with Windows PowerShell console, you have not only the simplicity of
the command prompt, but you also have the powerful Windows PowerShell language built
in. Therefore, if you need to refresh Group Policy three times and wait for five minutes
between refreshes, you can use the command appearing here (looping is covered in chapter
eleven).
To update help on your system, you must ensure two things. The first is that you open the
Windows PowerShell console with ADMIN rights. This is because the Windows PowerShell
help files reside in the protected Windows\System32\WindowsPowerShell directory. Once
you have launched the Windows PowerShell console with admin rights you need to ensure
your computer has Internet access so it can download and install the updated files. If your
computer does not have Internet connectivity, it will take several minutes before the
command times out (Windows PowerShell tries really hard to obtain the updated files). If you
run the Update-Help cmdlet with no parameters Windows PowerShell attempts to download
updated help for all modules stored in the default Windows PowerShell modules locations
that support updatable help. To run Update-Help more than once a day use the -Force
parameter as appears here.
Update-Help -Force
Even without downloading updated Windows PowerShell help, the help subsystem displays
the syntax of the cmdlet and other rudimentary information about the cmdlet. In this way.
To display help information from the internet, use the -Online switch. When used in this way,
Windows PowerShell causes the default browser to open to the appropriate page from the
Microsoft TechNet web site.
In the enterprise, network administrators may want to use the Save-Help cmdlet to download
help from the Internet. Once downloaded, the Update-Help cmdlet can point to the network
share for the files. This is an easy task to automate, and can run as a scheduled task.
Get-Command-ModuleNetAdapter
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-ModuleNetAdapter
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.
Get-Command-Modulenetadapter|Measure-Object
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:
Along the way, I will be showing some pretty cool Windows PowerShell tricks.
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
So how do I do it? I used to be able to find our real network card by finding the one that was
bound to TCP/IP. I would query the Win32_NetworkAdapterConfiguration WMI class, and
filter on the IPEnabled property. Using this approach, I would have done something like this:
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.
Identifying Adapters 32
Windows PowerShell Networking Guide
Get-WmiObject-ClassWin32\_NetworkAdapter|
Format-Table-PropertyName,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
---- -------------------
There are two things you will no doubt notice. The first is that most of the network adapters
report no status what-so-ever. The second thing you will notice is that the ones that do report
a status do so in some kind of code. The previous table is therefore pretty much useless! But
it does look nice.
Identifying Adapters 33
Windows PowerShell Networking Guide
A little work in the Windows SDK looking up the Win32_NetworkAdapter WMI class and I run
across the following information:
Value Meaning
0 Disconnected
1 Connecting
2 Connected
3 Disconnecting
5 Hardware disabled
6 Hardware malfunction
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.
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.
Identifying Adapters 34
Windows PowerShell Networking Guide
Using the association class with Windows PowerShell, I come up with the
FilterAssociatedNetworkAdapters.ps1 script shown here.
FilterAssociatedNetworkAdapters.ps1
Param($computer="localhost")
functionfunline ($strIN)
{
$num=$strIN.length
for($i=1 ; $i-le$num ; $i++)
{ $funline=$funline+"=" }
Write-Host-ForegroundColoryellow$strIN
Write-Host-ForegroundColordarkYellow$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")
functionfunline ($strIN)
{
$num=$strIN.length
for($i=1 ; $i-le$num ; $i++)
{ $funline=$funline+"=" }
Write-Host-ForegroundColoryellow$strIN
Write-Host-ForegroundColordarkYellow$funline
} #end funline
Identifying Adapters 35
Windows PowerShell Networking Guide
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.)
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.
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 -eq2)
{
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
Identifying Adapters 36
Windows PowerShell Networking Guide
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:
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:
Identifying Adapters 37
Windows PowerShell Networking Guide
If I have the advantage of Windows 8 or 8.1 or Windows Server 2012 or Windows Server
2012 R2, then I have the built in NetAdapter module. Due to the way that modules autoload
on Windows Powell I do not need to remember that I am using functions that exist in the
NetAdapter module. I can use either Windows PowerShell 3 or Windows PowerShell 4 and
the behavior will be the same (Windows 8.1 and Windows Server 2012 R2 come with
Windows PowerShell 4 and Windows 8 and Windows Server 2012 come with Windows
PowerShell 3).
The Get-NetAdapter cmdlet returns the name, interface description, index number, and
status of all network adapters present on the system. This is the default display of
information and appears in the figure that follows.
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.
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.
The command and output associated with the command appear in the figure that follows.
Identifying Adapters 38
Windows PowerShell Networking Guide
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.
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).
Identifying Adapters 39
Windows PowerShell Networking Guide
ifName : Ethernet\_7
AdminStatus : Down
MediaConnectionState : Unknown
LinkSpeed : 0 bps
PhysicalMediaType : 802.3
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|whereadminstatus-eq"up"
To find the disabled network adapters, I change the _adminstatus _from _up _to _down.
_This command appears here.
Get-NetAdapter|whereadminstatus-eq"down"
ifName : WiFi\_0
AdminStatus : Up
MediaConnectionState : Connected
LinkSpeed : 54 Mbps
PhysicalMediaType : Native 802.11
If I want to find any network adapters sniffing the network, I look for _promiscousmode.
_This command appears here.
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
Identifying Adapters 40
Windows PowerShell Networking Guide
command.
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'}
Identifying Adapters 41
Windows PowerShell Networking Guide
Identifying Adapters 42
Windows PowerShell Networking Guide
Question: You are troubleshooting your Windows 8.1 laptop and want to quickly enable all
network adapters. How can you do this?
Answer: Use the Get-NetAdapter and the Enable-NetAdapter commands. The command line
appears here:
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:
Option Explicit
Dim objShell
Dim objExec
Dim onWireLess
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
Sub subOUT
Do until objExec.StdOut.AtEndOfStream
strText = objExec.StdOut.ReadLine()
Wscript.Echo strText
Loop
End sub
Using WMI
Enabling and Disabling Adapters 44
Windows PowerShell Networking Guide
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.disable()
OR
$wmi.enable()
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:
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:
Credential
ds.GetWmiObjectCommand
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.
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.
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.
To suppress the prompt, I need to supply $false to the -confirm parameter. This appears
here.
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.
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.
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.
Confirm
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):y
Confirm
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):n
Question: You want to rename you network adapter. How can you do this using Windows
PowerShell on Windows 8 or above?
Answer: Use the Get-Netadapter function to retrieve the specific network adapter and
pipeline the results to the Rename-NetAdapter function. This technique appears here:
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 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:
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
Renaming Adapters 50
Windows PowerShell Networking Guide
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:
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:
The following figure shows using WMI to rename the network adapter.
Renaming Adapters 51
Windows PowerShell Networking Guide
On Windows 7 and Windows Server 2008 R2, it is not necessary to use the Get-WmiObject
cmdlet, assign new values for the property and call the Put method. This is because the Set-
CimInstance cmdlet permits accomplishing this feat as single command. The easiest way to
use Set-CimInstance is to use a query. Interestingly enough, this WQL query is the same
type of query that would have been used back in the VBScript days. The query to retrieve
the network adapter named Ethernet appears here:
To assign a new value for a property, I use a hashtable. The hashtable specifies the property
and the new value for the property. The hashtable to specify a value of RenamedConnection
for the NetConnectionID property appears here:
@{NetConnectionID="RenamedConnection"}
The complete Set-CimInstance command appears here (this is a single line command)
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.
Renaming Adapters 52
Windows PowerShell Networking Guide
Renaming a network adapter via Windows PowerShell requires admin rights. Unfortunately,
the help does not mention this. You just have to sort of know this. Luckily, an error occurs
when attempting to run the command without admin rights. The error is instructive, and
informs that access is denied. The error appears here.
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:
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).
Renaming Adapters 53
Windows PowerShell Networking Guide
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
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 -NameEther\*
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:
Renaming Adapters 54
Windows PowerShell Networking Guide
Renaming Adapters 55
Windows PowerShell Networking Guide
Question: You want to see which physical network adapters on your Windows 8.1 computer
using Windows PowerShell. How can you do this?
Answer: Use the -physical parameter with the Get-NetAdapter function and filter for a status
of up. This technique appears here:
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:
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.
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):
selectnetconnectionid,name,InterfaceIndex,netconnectionstatus
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
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
.Link
Http://www.ScriptingGuys.com
#>
Param(
[string]$computer=$env:COMPUTERNAME
) #end param
functionGet-StatusFromValue
{
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" }
}
Get-WmiObject-Classwin32\_networkadapter-computer$computer|
Select-ObjectName, @{LABEL="Status";
EXPRESSION={Get-StatusFromValue$\_.NetConnectionStatus}}
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:
Get-CimInstance-Classwin32\_networkadapter-computer$computer|
Select-ObjectName, @{LABEL="Status";
EXPRESSION={Get-StatusFromValue$\_.NetConnectionStatus}}
When I run the Get-StatusFromValue.ps1 script, in the Windows PowerShell ISE, I see the
output achieved here.
On Windows 8 and above the NetAdapter module contains the Get-NetAdapter function. To
see the status of all network adapters, use the Get-NetAdapter function with no parameters.
The command appears here:
Get-NetAdapter
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|wherestatus-eq'up'
The commands and the output from the two previous commands appear in the figure that
follows.
Wake on LAN and Wake on Wireless LAN. Improved wake patterns reduce the number
of false wakes. Beginning with Windows 7 a directed packet (such as a ping) does not
cause the computer to wake up.
ARP (Address Resolution Protocol) and NS (Neighbor Solicitation) offload. ARP and NS
packets do not wake up the computer. Instead the network adapter, beginning with
Windows 7, can respond. Therefore the computer does not need to wake up just to
maintain a presence on the network. This support depends on at least NDIS 6.0 drivers
and may not be available with older hardware.
Low Power on Media Disconnect. Enables the computer to place the network adapter
into a low power state when the network cable is unplugged and the computer is
running.
These settings are configurable via the graphical user interface by selecting the configure
button from the network adapter properties dialog box. The settings appear in the figure that
follows.
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.
Get-NetAdapterPowerManagement-Name ethernet
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:
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.
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:
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.
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:
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 change the computer name, network
interface name, and remove spaces until the second command appears on a single line).
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.
Question: You need to check on the network performance, but do not know where to begin.
How can you use Windows PowerShell to find networking counters?
Answer: Use the Get-Counter cmdlet and the -ListSet parameter. Select the
CounterSetName property and filter on names related to networking. The following
command returns sets related to IPV6.
NetSh
Using NetSh to obtain network statistics is easy and powerful. For example to show IP
statistics, I use the command appearing here.
A sample output from this command appears in the figure that follows.
To show TCP statistics using NetSh, I use the command appearing here.
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:
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:
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.
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.
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
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.
Interestingly enough, I can also use NetSh to report on TCP connections. The command
appears here:
The output from the command, as appears in the figure that follows, is a bit different than
that received from NetStat.
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.
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.
Next I use the paths with the Get-Counter cmdlet to retrieve a single instance of the IPv4
performance information. The command appears here.
The commands and the output from the commands appear in the figure that follows.
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.
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-NetAdapterStatistics
The command and a sample output appear in the figure that follows.
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.
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.
The command, and the output associated with the command appear in the figure that
follows.
Resources
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.
PowerShell.Org - Windows PowerShell community site containing blogs, forums, user group
information and a script repository.
Resources 79
Windows PowerShell Networking Guide
Resources 80