Windows Server 2012R2 - PowerShell
Windows Server 2012R2 - PowerShell
2012 R2 Windows
PowerShell
Fundamentals Hands-on lab
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter
in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document
does not give you any license to these patents, trademarks, copyrights, or other intellectual property.
Microsoft, Active Directory, Windows 7, Windows PowerShell, Windows Server 2012, and Windows Vista are trademarks of the
Microsoft group of companies.
Introduction
Estimated time to complete this lab
30 minutes
Objectives
In this lab, you will learn the fundamentals of using Windows PowerShell commands, known as cmdlets,
including the following techniques:
Windows PowerShell has a powerful documentation mechanism. Administrators can query the
help subsystem with a unified command set. Developers are provided with a set of common tools
to lower the time invested in documentation.
Constructing a pipeline
Windows PowerShell is different from other shells because it does not use strings as parameters;
instead it uses .NET objects which can be navigated, processed, reflected, and formatted.
Windows PowerShell does not limit the kind of formatting that can be applied to a simple object
nor does it place any restrictions on the destination of the output. Developers can extend the
wide range of available choices through the development of cmdlets.
As a complement to formatting, filtering and sorting commands are very useful for cmdlet output
manipulation. Windows PowerShell provides typical filtering and sorting cmdlets for most tasks,
and developers can also extend them by creating new cmdlets.
Like any Windows-based scripting language, Windows PowerShell has variables too, but they are
much more powerful than the variables in older scripting languages. Windows PowerShell
variables are actually mapped to underlying classes in the Microsoft .NET Framework. And in the
Framework, variables are objects, meaning they can store data and also manipulate it in many
ways.
The provider represents a set of stored data (e.g. the Microsoft Windows Registry, the Windows
file system, Active Directory) that can be accessed and navigated through Windows PowerShell
commands.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 3
Windows Server 2012 R2 Windows PowerShell Fundamentals
Prerequisites
Before working on this lab, you must have:
1. An understanding of concepts such as virtual machines, virtual hard disks, and virtual networks.
2. The ability to work in a command-line environment.
Intended audience
This lab is intended for network administrators who wish to learn the Windows PowerShell interface and
language.
Username: Administrator
Password: Passw0rd!
Note on activation
The virtual machines for these labs may have been built by using software that has not been activated.
This is by design in the lab to prevent the redistribution of activated software. The unactivated state of
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 4
Windows Server 2012 R2 Windows PowerShell Fundamentals
software has been taken into account in the design of the lab. Consequently, the lab is in no way affected
by this state. For operating systems other than Windows 8, please press Cancel or Close if prompted by an
activation dialog box. If you are prompted by an Activate screen for Windows 8, press the Windows key to
display the Start screen.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 5
Windows Server 2012 R2 Windows PowerShell Fundamentals
In this step, you will learn how to view the different levels of help content available for a cmdlet.
1. To open a new Windows PowerShell command window, on the taskbar, click Windows
PowerShell.
2. At the Windows PowerShell command prompt, type the following command, and then press
ENTER to see a list of available help topics.
help *
3. The command will fill an entire screen and then pause. Press ENTER to show the next output line,
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 6
Windows Server 2012 R2 Windows PowerShell Fundamentals
In the output you can see a second column with a value of Alias, Cmdlet, Provider, or HelpFile. An alias is
an alternative name for a command, usually an abbreviation or a name used by other shells for similar
functionality. Cmdlets are .NET classes that are exposed as APIs, commands, and GUIs. Providers are
extensions to Windows PowerShell that provide features such as policy verification or metadata
augmentation. Help files contain information for different topics, including command descriptions and
topics on how to extend Windows PowerShell.
4. Press SPACE BAR until the command prompt returns. Alternatively, you can type the letter Q to
cancel the output.
5. To view help information about the Get-Command cmdlet, at the Windows PowerShell command
help Get-Command
The help contains the syntax for the command as well as a brief description.
6. To see detailed help for the Get-Command cmdlet, at the Windows PowerShell command
The output includes details about the parameters for the cmdlet, as well as some examples.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 7
Windows Server 2012 R2 Windows PowerShell Fundamentals
7. To view the entire help content for the Get-Command cmdlet, at the Windows PowerShell
command prompt, type the following command, and then press ENTER.
Figure 4: View the entire help content for the Get-Command cmdlet
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 8
Windows Server 2012 R2 Windows PowerShell Fundamentals
The full help for the cmdlet includes parameter data types and notes. This is a technical view of the
commands help.
Help regarding conceptual topics in Windows PowerShell begins with the prefix about_. To display help
about a Windows PowerShell concept, type Get-Help followed by the concept name. To view a list of
1. To view the list of available commands, at the Windows PowerShell command prompt, type the
Get-Command
2. Review the list of commands available. Take note of the naming convention for commands with a
CommandType of Cmdlet.
Windows PowerShell uses verb-noun naming conventions to make cmdlets discoverable and obvious in
3. At the command prompt, type the following command, but do not press ENTER.
Get-C
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 9
Windows Server 2012 R2 Windows PowerShell Fundamentals
6. You can continue pressing TAB to cycle through all the available commands that begin with
Get-C. Similarly, you can cycle backwards by pressing SHIFT-TAB.
You can easily display a list of available Windows PowerShell commands. In addition, you can enter a
portion of a command name and use tab-completion to resolve the partial command to a full Windows
PowerShell command.
1. To view a list of services installed on the computer, at the Windows PowerShell command prompt,
type the following command, and then press ENTER.
Get-Service
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 10
Windows Server 2012 R2 Windows PowerShell Fundamentals
Windows PowerShell provides a complete set of verbs to query and manipulate services, including Get,
New, Restart, Resume, Set, Start, Stop, and Suspend. To view a list of service related commands type
Get-Command -Noun Service.
The Get-Service command resolves the first input as the name parameter when you do not specify a
parameter name for the input.
3. Enter the following command to obtain the same result as the previous step.
Get-Service Spooler
You can use positioned or named parameters when you invoke cmdlets. Windows PowerShell provides
built-in code that relieves cmdlet developers from having to parse program parameters.
4. Type the following command, and then press ENTER to view a list of all services that begin with
M.
Get-Service M*
Many cmdlets allow the use of wildcards. You can use the wildcard to filter the results to a subset of all
results.
5. Enter the following to see the same list of services. This time, the output is shown in list format.
Get-Service M* | Format-List
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 11
Windows Server 2012 R2 Windows PowerShell Fundamentals
In this example, there are two commands separated by a pipe (|) character. This means that the output
of the first command is used as the input to the second command.
6. Enter the following to see the same output, this time shown in a custom format.
Get-Service M* | Format-Custom
The status of all services beginning with M will be shown in the custom format.
Windows PowerShell includes several defined format commands, each one with many configuration
options. This provides a great deal of flexibility in output formatting. Developers can also create
additional format commands.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 12
Windows Server 2012 R2 Windows PowerShell Fundamentals
7. Type the following command, and then press ENTER to view all the running services that begin
with M.
Figure 11: Using the Where-Object command to filter the list to show only running services
In this command:
$_ refers to the input object (all services that begin with M).
-eq specifies that the left-hand argument, in this case the Status property ($_.Status), will be compared
for equality against the right-hand argument, the value Running.
8. To view all the stopped services that begin with M, type the following command, and then press
ENTER.
Figure 12: Using the Where-Object command to filter the list to show only stopped services
This is an example usage of the alias mechanism. Here, Where is an alias for the Where-Object
command.
9. To view a list of all services ordered by their status, type the following command, and then press
ENTER.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 13
Windows Server 2012 R2 Windows PowerShell Fundamentals
The Sort-Object command can order objects returned by a previous cmdlet using one or more of their
properties. You can also use the alias Sort to refer to the Sort-Object command.
10. Type the following command, and then press ENTER to view the Name and DisplayName of all
services beginning with M, with the output ordered and grouped by Status.
Figure 13: Using the Sort-Object and Format-Table command to group the output data
In this step, you will learn how to view the type members of those objects.
1. To view the type metadata for the object output by the Get-Service command, type the following
Get-Service | Get-Member
The type metadata for the object output by Get-Service is displayed. Note that the data type, in this
case the System.ServiceProcess.ServiceController class, is also displayed.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 14
Windows Server 2012 R2 Windows PowerShell Fundamentals
2. To view the type metadata for the object output by the Get-Process command, type the following
Get-Process | Get-Member
3. To create a new object of type System.Diagnostics.Process and view the type metadata for the
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 15
Windows Server 2012 R2 Windows PowerShell Fundamentals
4. Type the following command, and then press ENTER to view a list of services that the Spooler
service depends on.
Using Show-Command
Metadata information can also be used to identify the inputs needed for a specific command and to
retrieve information about the command. Windows PowerShell provides a graphical aid to provide the
command input.
In this task, you will learn how to retrieve and provide information needed in a graphical manner by using
the Show-Command cmdlet.
1. To view the input metadata for the Get-Service command, type the following command, and then
press ENTER.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 16
Windows Server 2012 R2 Windows PowerShell Fundamentals
Show-Command Get-Service
The input metadata fields for the Get-Service command are displayed. This is also an interactive window
that allows you to type the necessary fields to retrieve information from local or remote systems.
2. To view the results of Get-Service, in ComputerName, type localhost, and then click Run.
3. Review the results of the execution of Get-Service with the value for the ComputerName
parameter set to localhost.
The [Command] -WhatIf flag shows you the results without actually performing the action.
The [Command] -Confirm flag asks you to confirm the operation before it executes.
1. Type the following command, and then press ENTER to see a list of services that would be
Stop-Service M* -WhatIf
Figure 19: The Stop Service command with the WhatIf flag specified
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 17
Windows Server 2012 R2 Windows PowerShell Fundamentals
2. Type the following command, and then press ENTER to confirm whether or not to stop each
service.
Stop-Service M* -Confirm
For each service beginning with M, you will be asked if it should be stopped. For this lab, reply No in
each case.
Figure 20: The Stop-Service command with the confirm flag specified
1. To create a variable to hold a string value, type the following command, and then press ENTER.
With this command, you created a variable named var, and you assigned the string value Hi there to it.
A variable in Windows PowerShell must begin with the dollar sign ($). If special characters are needed in
a variable name, curly braces can be used to surround the variable name ({}).
2. To output the value stored in this variable, type the following command, and then press ENTER.
$var
A better way to output variable values is to use a cmdlet named Write-Host before the variable name,
Write-host $var
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 18
Windows Server 2012 R2 Windows PowerShell Fundamentals
By default, a variable will have a null value. Null values in Windows PowerShell are represented as $null.
3. Variables in Windows PowerShell can be listed and accessed under a special location. To display
the list of currently declared variables, type the following command, and then press ENTER.
Get-Variable
4. By default, variables in Windows PowerShell are non-typed, which means they can hold an
arbitrary value. To change the variable value and type to an integer, type the following command,
$var = 123
$var
5. Variables can also contain lists (similar to arrays). To change the value to an array of integers, type
$var = 1,2,3
$var
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 19
Windows Server 2012 R2 Windows PowerShell Fundamentals
6. To see the new type of the variable, type the following command, and then press ENTER.
$var.GetType().FullName
Arrays can be also manipulated through their .NET methods. For example, they can be queried on their
length.
7. To use the Length property to retrieve the number of elements of the array, type the following
command, and then press ENTER.
$var.Length
8. You can also access individual elements within an array by using square brackets ([]). To retrieve
the second element of the array, type the following command, and then press ENTER.
$var[1]
Arrays in Windows PowerShell are zero-based, which means that the first element will always be at
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 20
Windows Server 2012 R2 Windows PowerShell Fundamentals
9. You can also type a variable by prefixing its declaration with the desired data type name. To re-
declare the variable as an array of integers, type the following command, and then press ENTER.
10. To assign the string value 0123 to the third element of the array, and then display it, type the
$var[2] = "0123"
$var[2]
Examining the output of the variable, the string 0123 was converted into the number 123. Windows
PowerShell implicitly converted the stored value to match the destination variable type.
Implicit type conversions are done only for typed variables. Unlike strongly typed languages where a
variable can only be assigned an object of the correct type, Windows PowerShell allows the assignment
of any object, as long as it is convertible to the target type, by the extensive use of implicit conversions.
11. When an implicit conversion is not available, it displays an error. To attempt to set a string value
that cannot be converted, type the following command, and then press ENTER.
1. To create and initialize two string variables named var1 and var2, type the following commands,
pressing ENTER after each one.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 21
Windows Server 2012 R2 Windows PowerShell Fundamentals
$var2 = "world"
2. To use the plus (+) operator to concatenate the two string variables, type the following command,
$var1 + $var2
The result of this operation is a new Hello World string, as shown in the following screen shot.
Windows PowerShell defines the behavior of the + operator for numbers, strings, arrays and hash
tables. Adding two numbers produces a numeric result following the numeric widening rules. Adding
two strings performs a string concatenation, resulting in a new string, and adding two arrays joins the
3. You can use the .NET String properties to inspect the string objects. To use the Length property to
obtain the size in characters of the previous string concatenation, type the following command,
($var1 + $var2).Length
4. Windows PowerShell also provides other kinds of binary operators, like comparison operators. To
verify if two strings are equal, type the following command, and then press ENTER,
There are other comparison operators, like ne (not equals) gt (greater than), lt (less than),
ge (greater than or equal) and le (less than or equals).
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 22
Windows Server 2012 R2 Windows PowerShell Fundamentals
For each of these operators there is also a base or unqualified operator form, like eq and its two
variants ceq and ieq. The c variant is case-sensitive and the I variant is case-insensitive.
5. Formatting is a common task that can also be done in Windows PowerShell. To use a custom
format to display 12.4 as 12.40, type the following command, and then press ENTER.
"{0:f2}" -f 12.4
6. To display the same number as currency, and then to pad it to 10 characters aligned to the right,
"|{0,10:C}|" -f 12.4
The currency symbol configured in the current culture of the local machine is used.
7. Date and time formatting can also be done. To display only hours and minutes from the current
date, type the following command, and then press ENTER.
"{0:hh:mm}" -f (Get-Date)
In this step, you will learn how to create and run script files. To understand the reasons behind the
security features of Windows PowerShell, you will be introduced to a Windows PowerShell security feature
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 23
Windows Server 2012 R2 Windows PowerShell Fundamentals
called execution policies. The execution policy enables you to determine which Windows PowerShell
scripts (if any) will be allowed to run on your computer. Windows PowerShell has four different execution
policies:
Restricted No scripts are allowed to run. Windows PowerShell can only be used in interactive
mode.
AllSigned Only scripts signed by a trusted publisher can be run.
RemoteSigned Downloaded scripts must be signed by a trusted publisher before they can be
run.
Unrestricted No restrictions; all Windows PowerShell scripts can be run.
When you first install Windows PowerShell, the default value for the execution policy will be set to
Restricted.
1. To display the current execution policy, type the following command, and then press ENTER.
Get-ExecutionPolicy
2. Before running a script file, you will have to change the execution policy. To change the execution
policy to RemoteSigned and verify the change, type the following commands, pressing ENTER
Set-ExecutionPolicy Unrestricted
Get-ExecutionPolicy
Changing the execution policy requires administrative privileges. If you are running Windows Vista or
Windows 7, on the Start menu, right-click the Windows PowerShell icon, and then click Run as
Administrator.
For other platforms, either log in with an administrative account or open a Windows PowerShell console
by using the runas command and supplying appropriate credentials. For example:
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 24
Windows Server 2012 R2 Windows PowerShell Fundamentals
us/magazine/2007.09.powershell.aspx.
3. To create the script file, on the taskbar, right-click the Windows PowerShell icon, and then click
PowerShell Integrated Scripting Environment (ISE). The Windows PowerShell ISE is a host application
that enables you to run commands, write, test, and debug scripts in a friendly, syntax-colored, Unicode-
compliant environment.
The script pane at the top allows you to compose, edit, debug, and run functions and scripts.
Note that the script pane is not displayed by default. To display the script pane, on the View
The console pane at the bottom is used for running interactive commands, just as you would
5. In the script pane, type the following commands, pressing ENTER after each line.
# test.ps1
# Show Hello and time.
"" # Blank Line
"Hello " + $env:UserName + "!"
"Time is " + "{0:HH}:{0:mm}" -f (Get-Date)
"" # Blank Line
6. To save the file as a Windows PowerShell script file, on the File menu, click Save As.
7. In the file name, type test.ps1, in the location, type C:\users\Administrator\Desktop, and then
click Save.
When you create your script file, the filename must have a .ps1 extension.
8. Click in the command pane, type the following command, and then press ENTER.
cd C:\users\Administrator\Desktop
9. To execute the script file you created in the previous step, type the following command, and then
press ENTER.
.\test.ps1
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 25
Windows Server 2012 R2 Windows PowerShell Fundamentals
You can follow the same procedure to execute scripts in the Windows PowerShell text-based console.
From the ISE, you can also execute a script using the Run command on the File menu.
Preceding the script name with directory information, in this case the current directory (.\), instructs
There must be no space between .\ and the script name. Adding the .ps1 extension is optional. You
must specify the path to the script file, even if the script is in the current directory.
Figure 38: Running the script file from the current directory
10. To use the Invoke-Expression command as an alternative way of running the same script, type the
Invoke-Expression "C:\Users\Administrator\Desktop\test.ps1"
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 26
Windows Server 2012 R2 Windows PowerShell Fundamentals
11. To use the invoke operator (&) to execute the command in the string that follows, type the
& "C:\Users\Administrator\Desktop\test.ps1"
12. To close the test.ps1 script, on the test.ps1 tab, click the X.
As an alternative, on the File menu, click Close.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 27
Windows Server 2012 R2 Windows PowerShell Fundamentals
Many commands in the ISE have keyboard shortcuts. You can see the keyboard shortcuts to the right of
their respective commands in the menus at the top of the ISE. The keyboard shortcut to close the active
file in the script pane is Ctrl+F4.
Creating functions
In Windows PowerShell, you can declare functions. Functions are reusable pieces of code that can be
called as many times as you want after you declare them.
In this step, you will declare a function, learn about using different types of parameters, and specify
default values for these parameters.
function Get-Soup (
[switch] $please,
[string] $soup = "chicken noodle"
)
{
if ($please) {
"Here's your $soup soup"
}
else {
"No soup for you!"
}
}
This command declares a Get-Soup function which will receive two parameters, $please and $soup.
3. To run the script, press F5, and then click the Script arrow to hide the script pane.
It is not necessary to save a script before executing it in the ISE. This makes it easy to use the script pane
to quickly test commands and code snippets.
4. To call the script with no parameters, in the command pane, type the following command, and
Get-Soup
5. To call the Get Soup function with the $please parameter, type the following command, and then
press ENTER.
To specify a parameter declared as a switch, specify parameter name after the function name.
Get-Soup -please
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 28
Windows Server 2012 R2 Windows PowerShell Fundamentals
Since you didnt specify a value for the $soup parameter, the default value (chicken noodle) is used.
6. To call Get-Soup specifying a value for $soup, type the following command, and then press
ENTER.
In this step, you will list the available providers and the drives which make use of these providers. You will
also create a new drive using the registry provider.
Get-PSProvider
3. To display a list of the available drives, type the following command, and then press ENTER.
Get-PSDrive
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 29
Windows Server 2012 R2 Windows PowerShell Fundamentals
4. To create a new drive for the HKEY_CLASSES_ROOT hive in the registry using the Registry
As with the file system, the registry can also be modified using Windows PowerShell drives. Be aware
that when modifying the registry, changes may cause the system to fail.
5. To browse to the newly created drive, called HKCS, as if you were working with a drive in the file
system, type the following commands, pressing ENTER after each one.
cd HKCS:
dir .ht*
This will set the current location to the newly created HKCS drive, and then display the list of registry
entries that match the filter expression.
IMPORTANT: The trailing colon (:) after the drive name indicates a drive change which is different from
a folder change. The colon is necessary; otherwise, Windows PowerShell will display an error.
6. To change the current folder to another folder inside the HKCS drive, and then list its contents,
cd .html
dir
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 30
Windows Server 2012 R2 Windows PowerShell Fundamentals
Figure 45: Listing a key of the registry as if it were a folder in the file system
Many of the same commands used to manipulate the file system, such as cd and dir, also work with
other providers.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 31
Windows Server 2012 R2 Windows PowerShell Fundamentals
Using the Windows PowerShell ISE gives you many different advantages when creating scripts. Although it
can be used for interactive commands, the best use of the tool is for script creation and debugging.
1. To open a new Windows PowerShell ISE environment window, on the taskbar, right-click
loaded.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 32
Windows Server 2012 R2 Windows PowerShell Fundamentals
Figure 47: Windows PowerShell ISE with the script pane displayed
2. As you type, you will see a list of possible commands. Continue typing Get-Ser.
Get-Service will be selected and the possible complete syntax will be displayed.
3. Press TAB.
4. Press SPACE BAR.
5. Type -.
A list of possible parameters will appear.
6. Continue typing Computer, press TAB, and then press SPACE BAR.
7. Type DC.
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 33
Windows Server 2012 R2 Windows PowerShell Fundamentals
3. In the ComputerName parameter, type DC, and then press F5 to run the command.
Review the results of all available services on the target system.
4. In the Name parameter, type TermService, and then press F5 to run the command.
5. In the command pane, select the Insert option.
The command will be inserted into the interactive Windows PowerShell console pane.
1.2. In the script pane, type the following command, and then press ENTER.
2.3. To access the snippets, press Ctrl+J, type foreach, and then press TAB.
The following block will be displayed:
{
}
$item.name
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 34
Windows Server 2012 R2 Windows PowerShell Fundamentals
$item.name
}
Lab created by HynesITe, Inc. For questions or comments, send an email message to [email protected] Page | 35