Jump to content

PowerShell/Collection

From Wikiversity

PowerShell

[edit | edit source]

Learning Guide

[edit | edit source]

This learning guide supports the Wikiversity course PowerShell, available at http://en.wikiversity.org/wiki/PowerShell.

Overview

[edit | edit source]

Part of the Information Technology SchoolPowerShell/Collection/Sidebar

PowerShell (including Windows PowerShell and PowerShell Core) is a task automation and configuration management framework from Microsoft available since 2006, consisting of a command-line shell and associated scripting language built on the .NET Framework. Initially a Windows component only, PowerShell was made open-source and cross-platform on 18 August 2016.[1]

This entire Wikiversity course can be downloaded in book form by selecting Download Learning Guide in the sidebar.

Approach

[edit | edit source]

Many PowerShell tutorials approach PowerShell from a command-line scripting and automation perspective, assuming that you already know programming. This course takes a more traditional academic introduction to programming approach, with the assumption that once you understand programming using the PowerShell language, you will be able to use other resources to develop the scripts you need.

Preparation

[edit | edit source]

This is a third-semester, college-level course. Learners should already be familiar with introductory computer concepts and computer support concepts.

Resources

[edit | edit source]

The lessons in this course use a variety of information resources. All are free, but some require registration in order to access them. On Wikiversity, every effort is made to avoid this type of resource unless the quality of the resource clearly outweighs the nuisance factor. The online book Master-PowerShell | With Dr. Tobias Weltner at PowerShell.com is a high quality resource, and provides the option of opting out of any contact.

Lessons

[edit | edit source]
  1. Introduction
  2. Console
  3. ISE
  4. Variables
  5. Expressions
  6. Conditions
  7. Loops
  8. Arrays and Hash Tables
  9. Functions
  10. Errors
  11. File System
  12. Registry
  13. Systems Management
  14. Event Logs
  15. Additional Topics

Examples

[edit | edit source]

See Also

[edit | edit source]

Bibliography

[edit | edit source]

References

[edit | edit source]
Educational level: this is a tertiary (university) resource.
Completion status: this resource is considered to be complete.

Lesson 1 - Introduction

[edit | edit source]

This lesson introduces Windows PowerShell by looking at the PowerShell environment. Activities include PowerShell, PowerShell ISE, and the Get-Host, Get-Help, and Update-Help cmdlets.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Explain basic Windows PowerShell concepts.
  • Describe the Microsoft resources available for learning Windows PowerShell.
  • Start Windows PowerShell and Windows PowerShell ISE.
  • Run the Get-Host cmdlet in Windows PowerShell and Windows PowerShell ISE.
  • Get and update help in Windows PowerShell.

Readings

[edit | edit source]
  1. Wikipedia: Windows PowerShell
  2. Wikipedia: .NET Framework
  3. Microsoft Technet: Getting Started with Windows PowerShell

Multimedia

[edit | edit source]
  1. YouTube: PowerShell: Introduction and Scripting Tutorial

Examples

[edit | edit source]

Get-Help

[edit | edit source]

The Get-Help cmdlet displays information about Windows PowerShell commands and concepts.[1]

Get-Help

Get-Host

[edit | edit source]

The Get-Host cmdlet gets an object that contains the current host program (ConsoleHost or Windows PowerShell ISE Host), Windows PowerShell version, and culture (region) settings.[2]

Get-Host

Update-Help

[edit | edit source]

The Update-Help cmdlet downloads and installs the newest help files on your computer.[3]

Update-Help

Activities

[edit | edit source]
  1. Review Microsoft: Windows PowerShell. Identify the different resources available to learn and use PowerShell, and the different versions of PowerShell available for download.
  2. Review Microsoft TechNet: What's New in Windows PowerShell. Determine whether you have the most recent version of Windows PowerShell installed. If not, consider downloading and installing the current version. Version 3.0 or later should be used for this course. Watch YouTube: Update PowerShell if you need help updating PowerShell.
  3. Review Microsoft MSDN: Starting Windows PowerShell. Start PowerShell. Then start PowerShell ISE. Compare the two PowerShell environments.
  4. Review Microsoft TechNet: Using the Get-Host Cmdlet. Run the Get-Host cmdlet in both PowerShell and PowerShell ISE. Observe the differences between the two environments. Verify which version of Windows PowerShell is installed.
  5. Review Microsoft TechNet: Understanding and Using Updatable PowerShell Help. Run PowerShell as an administrator and then run the Update-Help cmdlet to ensure you have the latest PowerShell help files installed.
  6. Review Microsoft TechNet: Using the Get-Help Cmdlet. Use the Get-Help cmdlet to learn more about the Get-Host cmdlet:
    Get-Help Get-Host
    
  7. Review Microsoft: Windows PowerShell Quick Reference. Download the reference and print or save it for future use.

Lesson Summary

[edit | edit source]
  • Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework.[4]
  • PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems.[5]
  • Administrative tasks in PowerShell are generally performed by cmdlets.[6]
  • PowerShell console help is accessed using the Get-Help cmdlet and is updatable with fresh content using the Update-Help cmdlet.[7]
  • PowerShell can execute four kinds of named commands: cmdlets, scripts, functions, and executable programs.[8]
  • PowerShell scripts are saved with a .ps1 file extension.[9]
  • Cmdlets follow a <verb>—<noun> naming pattern.[10]
  • Cmdlets output their results as objects.[11]
  • PowerShell implements the concept of a pipeline, which enables the output of one cmdlet to be piped as input to another cmdlet.[12]
  • PowerShell pipelines are used to compose complex commands, using the | operator to connect stages.[13]
  • Windows PowerShell includes a dynamically typed scripting language which supports variables, functions, conditions, loops, structured error/exception handling, as well as integration with .NET.[14]
  • Variables in PowerShell scripts have names that start with $, and they can be assigned any value, including the output of cmdlets.[15]
  • $_ refers to the current object in the pipeline.[16]
  • PowerShell script execution is disabled by default and must be enabled explicitly.[17]
  • PowerShell 2.0 is integrated with Windows 7 and Windows Server 2008 R2.[18]
  • PowerShell 3.0 is integrated with Windows 8 and Windows Server 2012.[19]
  • PowerShell 4.0 is integrated with Windows 8.1 and Windows Server 2012 R2.[20]
  • PowerShell 3.0 and 4.0 may be installed on Windows 7 and later operating systems.[21]

Key Terms

[edit | edit source]
CMD.EXE
The Microsoft-supplied command-line interpreter on OS/2 and eComStation, Windows CE and on Windows NT-based operating systems (including Windows 2000, XP, Vista, 7, 8, Server 2003, Server 2008, Server 2008 R2 and Server 2012).[22]
Component Object Model (COM)
A binary-interface standard for software components introduced by Microsoft in 1993 used to enable inter-process communication and dynamic object creation in a large range of programming languages.[23]
COMMAND.COM
The filename of the default operating system shell for DOS operating systems and the default command line interpreter on Windows 95, Windows 98 and Windows ME.[24]
compiler
A computer program (or set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language, often having a binary form known as object code).[25]
console
A command-line interface (CLI) used as a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines).[26]
Get-Help
Retrieves a list of all available help topics.[27]
Get-Host
Gets an object that represents the current host program.[28]
interpreted language
An interpreted language is a programming language for which most of its implementations execute instructions directly, without previously compiling a program into machine-language instructions.[29]
.NET Framework
A software framework developed by Microsoft that runs primarily on Microsoft Windows which includes a large class library known as Framework Class Library (FCL) and provides language interoperability across several programming languages.[30]
pipeline
A set of data processing elements connected in series, where the output of one element is the input of the next one.[31]
scripting language
A programming language that supports scripts, programs written for a special run-time environment that can interpret (rather than compile) and automate the execution of tasks that could alternatively be executed one-by-one by a human operator.[32]
shell
A user interface for access to an operating system's services. In general, operating system shells use either a command-line interface (CLI) or graphical user interface (GUI), depending on a computer's role and particular operation.[33]
Update-Help
Downloads and installs the newest help files on your computer.[34]
Windows Management Instrumentation (WMI)
A set of extensions to the Windows Driver Model that provides an operating system interface through which instrumented components provide information and notification. WMI allows scripting languages like VBScript or Windows PowerShell to manage Microsoft Windows personal computers and servers, both locally and remotely.[35]
Windows Script Host (WSH)
An automation technology for Microsoft Windows operating systems that provides scripting abilities comparable to batch files, but with a wider range of supported features.[36]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Windows PowerShell is a _____ and _____ from Microsoft, consisting of a _____ and _____ built on the _____.
Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework.
2. PowerShell provides full access to _____ and _____, enabling administrators to perform administrative tasks on _____.
PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems.
3. Administrative tasks in PowerShell are generally performed by _____.
Administrative tasks in PowerShell are generally performed by cmdlets.
4. PowerShell console help is accessed using the _____ cmdlet and is updatable with fresh content using the _____ cmdlet.
PowerShell console help is accessed using the Get-Help cmdlet and is updatable with fresh content using the Update-Help cmdlet.
5. PowerShell can execute four kinds of named commands: _____, _____, _____, and _____.
PowerShell can execute four kinds of named commands: cmdlets, scripts, functions, and executable programs.
6. PowerShell scripts are saved with a _____ file extension.
PowerShell scripts are saved with a .ps1 file extension.
7. Cmdlets follow a _____ naming pattern.
Cmdlets follow a <verb>—<noun> naming pattern.
8. Cmdlets output their results as _____.
Cmdlets output their results as objects.
9. PowerShell implements the concept of a _____, which enables the output of one cmdlet to be _____ as input to another cmdlet.
PowerShell implements the concept of a pipeline, which enables the output of one cmdlet to be piped as input to another cmdlet.
10. PowerShell _____ are used to compose complex commands, using the _____ operator to connect stages.
PowerShell pipelines are used to compose complex commands, using the
11. Windows PowerShell includes a dynamically typed scripting language which supports _____, _____, _____, _____, _____, as well as integration with _____.
Windows PowerShell includes a dynamically typed scripting language which supports variables, functions, conditions, loops, structured error/exception handling, as well as integration with .NET.
12. Variables in PowerShell scripts have names that start with _____, and they can be assigned _____.
Variables in PowerShell scripts have names that start with $, and they can be assigned any value, including the output of cmdlets.
13. _____ refers to the current object in the pipeline.
$_ refers to the current object in the pipeline.
14. PowerShell script execution is _____ by default and must be _____ explicitly.
PowerShell script execution is disabled by default and must be enabled explicitly.
15. PowerShell 2.0 is integrated with _____.
PowerShell 2.0 is integrated with Windows 7 and Windows Server 2008 R2.
16. PowerShell 3.0 is integrated with _____.
PowerShell 3.0 is integrated with Windows 8 and Windows Server 2012.
17. PowerShell 4.0 is integrated with _____.
PowerShell 4.0 is integrated with Windows 8.1 and Windows Server 2012 R2.
18. PowerShell 3.0 and 4.0 may be installed on _____ and later operating systems.
PowerShell 3.0 and 4.0 may be installed on Windows 7 and later operating systems.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 2 - Console

[edit | edit source]

This lesson introduces the PowerShell console by looking at cmdlets, the pipeline, and redirection.


Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Customize the PowerShell console interface.
  • Use the PowerShell console interface to run cmdlets.
  • Use the PowerShell pipeline to select, sort, and filter content.
  • Use redirection to save PowerShell output as a file.

Readings

[edit | edit source]
  1. Wikipedia: Command-line interface
  2. Wikipedia: Pipeline (Unix)
  3. Wikipedia: Redirection (computing)
  4. Wikipedia: Comment (computer programming)
  5. BonusBits: Mastering PowerShell Chapter 1 - The PowerShell Console

Multimedia

[edit | edit source]
  1. Microsoft Virtual Academy: Getting Started with PowerShell 3.0
  2. YouTube: Customizing the Shell

Examples

[edit | edit source]

Comments

[edit | edit source]

Comments are added to a PowerShell script using the hashtag or number sign character (#).[1]

# This is a PowerShell comment.

Block Comments

[edit | edit source]

Block comments are added to a PowerShell script using <# and #>.[2]

<#

This is a series or
block of comments.

#>

Get-Command

[edit | edit source]

The Get-Command cmdlet lists all PowerShell commands.[3]

Get-Command  # List all PowerShell commands.

Get-Date

[edit | edit source]

The Get-Date cmdlet returns the current date and time.[4]

Get-Date  # Get the current date and time.

Get-Process

[edit | edit source]

The Get-Process cmdlet lists all running processes.[5]

Get-Process  # List all running processes.

Get-Service

[edit | edit source]

The Get-Service cmdlet lists all installed services.[6]

Get-Service  # List all installed services.

Select-Object

[edit | edit source]

The Select-Object cmdlet selects objects or object properties.[7]

Get-Host | Select-Object 'Name'  # Displays the host's Name property only.

Sort-Object

[edit | edit source]

The Sort-Object cmdlet sorts objects based on property values.[8]

Get-Service | Sort-Object 'Status'  # Displays services sorted by Status.

Where-Object

[edit | edit source]

The Where-Object cmdlet selects objects based on their property values.[9]

Get-Process | Where-Object 'CPU' -GT 0  # Displays processes where the CPU utilization is greater than 0.

Redirection

[edit | edit source]

The > character is used to redirect pipeline output to a file. The >> combination appends pipeline output to the file.[10]

Get-Date > hostinfo.txt   # Create hostinfo.txt file with current date
Get-Host >> hostinfo.txt  # Append host information
Notepad hostinfo.txt    # Open hostinfo.txt in Notepad to view results

Activities

[edit | edit source]
  1. Experiment with customizing the PowerShell console properties, including font, screen buffer size, and colors.
  2. Review Microsoft TechNet: Using the Select-Object Cmdlet. Use PowerShell, the Get-Host and Select-Object cmdlets, and the pipeline to select the name of the host environment. Then use PowerShell ISE to test the same command.
  3. Use the Get-Host and Select-Object cmdlets and the pipeline to select the PowerShell version number.
  4. Review Microsoft TechNet: Using the Get-Command Cmdlet. Run the Get-Command cmdlet and redirect the output to a file. Open the file to view the results.
  5. Review Microsoft TechNet: Using the Get-Process Cmdlet and Microsoft TechNet: Using the Sort-Object Cmdlet. Use a combination of Get-Process and Sort-Object to display a list of the running processes sorted by CPU usage in descending order (greatest to least).
  6. Review Microsoft TechNet: Using the Get-Service Cmdlet and Microsoft TechNet: Using the Where-Object Cmdlet. Use the correct combination of Get-Service, Select-Object, Sort-Object, and Where-Object to display a list of running services sorted in alphabetical order by display name, showing the display name only.

Lesson Summary

[edit | edit source]
  • A command-line interface (CLI), also known as command-line user interface, console user interface, and character user interface (CUI), is a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines).[11]
  • The interface is usually implemented with a command line shell, which is a program that accepts commands as text input and converts commands to appropriate operating system functions.[12]
  • Programs with command-line interfaces are generally easier to automate via scripting.[13]
  • A command prompt (or just prompt) is a sequence of (one or more) characters used in a command-line interface to indicate readiness to accept commands.[14]
  • A CLI can generally be considered as consisting of syntax and semantics.[15]
  • The syntax is the grammar that all commands must follow. These rules also dictate how a user navigates through the system of commands.[16]
  • The semantics define what sort of operations are possible, on what sort of data these operations can be performed, and how the grammar represents these operations and data—the symbolic meaning in the syntax.[17]
  • A command-line argument or parameter is an item of information provided to a program when it is started.[18]
  • A command-line option or simply option (also known as a flag or switch) modifies the operation of a command.[19]
  • Although most users think of the shell as an interactive command interpreter, it is really a programming language in which each statement runs a command.[20]
  • A pipeline is a set of processes chained by their standard streams, so that the output of each process feeds directly as input to the next one.[21]
  • To use the pipeline, one writes the commands in sequence, separated by the ASCII vertical bar character "|" (which, for this reason, is often called "pipe character").[22]
  • By default, the standard error streams of the processes in a pipeline are not passed on through the pipe; instead, they are merged and directed to the console.[23]
  • Redirection is a function common to most command-line interpreters that can redirect standard streams to user-specified locations.[24]
  • Redirection is usually implemented by placing certain characters between commands. Typically, the syntax of these characters is as follows, using < to redirect input, and > to redirect output.[25]
  • To append output to the end of the file, rather than overwriting it, use the >> operator.[26]
  • A comment is a programming language construct used to embed programmer-readable annotations in the source code of a computer program.[27]
  • Comments are added to a PowerShell script using the hashtag or number sign character (#).[28]
  • Block comments are added to a PowerShell script using <# and #>.[29]
  • The name of the PowerShell console executable program is powershell.exe.[30]
  • PowerShell commands are cancelled by pressing <Ctrl>+<C>.[31]
  • The <Tab> key is used to complete PowerShell input automatically.[32]
  • The PowerShell console font, window size, buffer size, and other options are configured using the console Properties dialog box.[33]
  • PowerShell output may be displayed one page at a time by piping output through the More function, as in command | more.[34]
  • The Get-Command cmdlet lists all PowerShell commands.[35]
  • The Get-Date cmdlet returns the current date and time.[36]
  • The Get-Process cmdlet lists all running processes.[37]
  • The Get-Service cmdlet lists all installed services.[38]
  • The Select-Object cmdlet selects objects or object properties.[39]
  • The Sort-Object cmdlet sorts objects based on property values.[40]
  • The Where-Object cmdlet selects objects based on their property values.[41]

Key Terms

[edit | edit source]
argument
One of the pieces of data provided as input in a parameter to a subroutine.[42]
buffer
A region of a physical memory storage used to temporarily store data while it is being moved from one place to another.[43]
default
A setting or a value automatically assigned to a software application, computer program or device, outside of user intervention.[44]
delimiter
A sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data streams.[45]
environment variable
A dynamic named value that can affect the way running processes will behave on a computer.[46]
escape character
A character which invokes an alternative interpretation on subsequent characters in a character sequence.[47]
option
Text that modifies the operation of a command, with the effect determined by the command's program.[48]
parameter
A special kind of variable, used in a subroutine to refer to one of the pieces of data, or arguments, provided as input to a subroutine.[49]
pseudocode
An informal high-level description of the operating principle of a computer program or other algorithm.[50]
stdin (standard input)
The stream of data (often text) going into a program.[51]
stdout (standard output)
The stream where a program writes its output data.[52]
stderr (standard error)
Another output stream typically used by programs to output error messages or diagnostics.[53]
stream
A sequence of data elements made available over time.[54]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. A command-line interface (CLI), also known as command-line user interface, console user interface, and character user interface (CUI), is a means of interacting with a computer program where the user (or client) _____.
A command-line interface (CLI), also known as command-line user interface, console user interface, and character user interface (CUI), is a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines).
2. The interface is usually implemented with a command line shell, which is _____.
The interface is usually implemented with a command line shell, which is a program that accepts commands as text input and converts commands to appropriate operating system functions.
3. Programs with command-line interfaces are generally easier to _____.
Programs with command-line interfaces are generally easier to automate via scripting.
4. A command prompt (or just prompt) is a _____.
A command prompt (or just prompt) is a sequence of (one or more) characters used in a command-line interface to indicate readiness to accept commands.
5. A CLI can generally be considered as consisting of _____.
A CLI can generally be considered as consisting of syntax and semantics.
6. The syntax is _____.
The syntax is the grammar that all commands must follow. These rules also dictate how a user navigates through the system of commands.
7. The semantics define _____.
The semantics define what sort of operations are possible, on what sort of data these operations can be performed, and how the grammar represents these operations and data—the symbolic meaning in the syntax.
8. A command-line argument or parameter is _____.
A command-line argument or parameter is an item of information provided to a program when it is started.
9. A command-line option or simply option (also known as a flag or switch) _____.
A command-line option or simply option (also known as a flag or switch) modifies the operation of a command.
10. Although most users think of the shell as an interactive command interpreter, it is really _____.
Although most users think of the shell as an interactive command interpreter, it is really a programming language in which each statement runs a command.
11. A pipeline is _____.
A pipeline is a set of processes chained by their standard streams, so that the output of each process feeds directly as input to the next one.
12. To use the pipeline, one _____.
To use the pipeline, one writes the commands in sequence, separated by the ASCII vertical bar character "
13. By default, the standard error streams of the processes in a pipeline _____.
By default, the standard error streams of the processes in a pipeline are not passed on through the pipe; instead, they are merged and directed to the console.
14. Redirection is a function common to most command-line interpreters that can _____.
Redirection is a function common to most command-line interpreters that can redirect standard streams to user-specified locations.
15. Redirection is usually implemented by placing certain characters between commands. Typically, the syntax of these characters is as follows, using _____ to redirect input, and _____ to redirect output.
Redirection is usually implemented by placing certain characters between commands. Typically, the syntax of these characters is as follows, using < to redirect input, and > to redirect output.
16. To append output to the end of the file, rather than overwriting it, use the _____ operator.
To append output to the end of the file, rather than overwriting it, use the >> operator.
17. A comment is a programming language construct used to _____.
A comment is a programming language construct used to embed programmer-readable annotations in the source code of a computer program.
18. Comments are added to a PowerShell script using _____.
Comments are added to a PowerShell script using the hashtag or number sign character (#).
19. Block comments are added to a PowerShell script using _____.
Block comments are added to a PowerShell script using <# and #>.
20. The name of the PowerShell console executable program is _____.
The name of the PowerShell console executable program is powershell.exe.
21. PowerShell commands are cancelled by pressing _____.
PowerShell commands are cancelled by pressing <Ctrl>+<C>.
22. The <Tab> key is used to _____.
The <Tab> key is used to complete PowerShell input automatically.
23. The PowerShell console font, window size, buffer size, and other options are configured using _____.
The PowerShell console font, window size, buffer size, and other options are configured using the console Properties dialog box.
24. PowerShell output may be displayed one page at a time by _____.
PowerShell output may be displayed one page at a time by piping output through the More function, as in command
25. The Get-Command cmdlet _____.
The Get-Command cmdlet lists all PowerShell commands.
26. The Get-Date cmdlet _____.
The Get-Date cmdlet returns the current date and time.
27. The Get-Process cmdlet _____.
The Get-Process cmdlet lists all running processes.
28. The Get-Service cmdlet _____.
The Get-Service cmdlet lists all installed services.
29. The Select-Object cmdlet _____.
The Select-Object cmdlet selects objects or object properties.
30. The Sort-Object cmdlet _____.
The Sort-Object cmdlet sorts objects based on property values.
31. The Where-Object cmdlet _____.
The Where-Object cmdlet selects objects based on their property values.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.
  1. Wikipedia: Comparison of programming languages (syntax)
  2. Wikipedia: Comparison of programming languages (syntax)
  3. Microsoft TechNet: Get-Command
  4. Microsoft TechNet: Get-Date
  5. Microsoft TechNet: Get-Process
  6. Microsoft TechNet: Get-Service
  7. Microsoft TechNet: Select-Object
  8. Microsoft TechNet: Sort-Object
  9. Microsoft TechNet: Where-Object
  10. Microsoft TechNet: about_Redirection
  11. Wikipedia: Command-line interface
  12. Wikipedia: Command-line interface
  13. Wikipedia: Command-line interface
  14. Wikipedia: Command-line interface
  15. Wikipedia: Command-line interface
  16. Wikipedia: Command-line interface
  17. Wikipedia: Command-line interface
  18. Wikipedia: Command-line interface
  19. Wikipedia: Command-line interface
  20. Wikipedia: Command-line interface
  21. Wikipedia: Pipeline (Unix)
  22. Wikipedia: Pipeline (Unix)
  23. Wikipedia: Pipeline (Unix)
  24. Wikipedia: Redirection (computing)
  25. Wikipedia: Redirection (computing)
  26. Wikipedia: Redirection (computing)
  27. Wikipedia: Comment (computer programming)
  28. Wikipedia: Comparison of programming languages (syntax)
  29. Wikipedia: Comparison of programming languages (syntax)
  30. Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
  31. Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
  32. Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
  33. Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
  34. Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
  35. Microsoft TechNet: Get-Command
  36. Microsoft TechNet: Get-Date
  37. Microsoft TechNet: Get-Process
  38. Microsoft TechNet: Get-Service
  39. Microsoft TechNet: Select-Object
  40. Microsoft TechNet: Sort-Object
  41. Microsoft TechNet: Where-Object
  42. Wikipedia: Parameter (computer programming)
  43. Wikipedia: Data buffer
  44. Wikipedia: Default (computer science)
  45. Wikipedia: Delimiter
  46. Wikipedia: Environment variable
  47. Wikipedia: Escape character
  48. Wikipedia: Command-line option
  49. Wikipedia: Parameter (computer programming)
  50. Wikipedia: Pseudocode
  51. Wikipedia: Standard streams
  52. Wikipedia: Standard streams
  53. Wikipedia: Standard streams
  54. Wikipedia: Stream (computing)

Lesson 3 - ISE

[edit | edit source]

This lesson introduces PowerShell ISE, the integrated scripting environment by examining the scripting environment, automatic code completion, and by creating simple scripts.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Modify execution policy settings to allow locally written scripts to run.
  • Understand cmdlet aliases.
  • Explain the difference between Write-Host and Write-Output.
  • Use Write-Output to display messages to the user.
  • Stop and start services using a PowerShell script.

Readings

[edit | edit source]
  1. Wikipedia: Integrated development environment
  2. Wikipedia: Intelligent code completion
  3. Microsoft TechNet: Using the Windows PowerShell ISE
  4. BonusBits: Mastering PowerShell Chapter 2 - Interactive PowerShell

Multimedia

[edit | edit source]
  1. YouTube: Microsoft Windows 8 First Look: Windows PowerShell
  2. Microsoft Virtual Academy: Advanced Tools & Scripting with PowerShell 3.0

Examples

[edit | edit source]

Get-Alias

[edit | edit source]

The Get-Alias cmdlet displays a list of current Windows PowerShell aliases.[1]

Get-Alias    # List current aliases.

Get-ExecutionPolicy

[edit | edit source]

The Get-ExecutionPolicy cmdlet returns the current Windows PowerShell execution policy security level.[2]

Get-ExecutionPolicy    # Show the current PowerShell execution policy security level.

Set-ExecutionPolicy

[edit | edit source]

The Set-ExecutionPolicy cmdlet sets the Windows PowerShell execution policy security level.[3]

Set-ExecutionPolicy RemoteSigned    # Set the current execution policy security level to RemoteSigned.

Start-Service

[edit | edit source]

The Start-Service cmdlet starts a stopped service or services.[4] Starting services on Windows requires running PowerShell or the corresponding script as an administrator.

Start-Service 'Spooler'    # Start the Print Spooler service.

Stop-Service

[edit | edit source]

The Stop-Service cmdlet stops a running service or services.[5] Stopping services on Windows requires running PowerShell or the corresponding script as an administrator.

Stop-Service 'Spooler'    # Stop the Print Spooler service.

Write-Host

[edit | edit source]

The Write-Host cmdlet writes directly to the host environment, bypassing the pipeline.[6]

Write-Host 'Hello PowerShell!'

Write-Output

[edit | edit source]

The Write-Output cmdlet writes to the pipeline.[7]

Write-Output 'Hello PowerShell!'

Comparing Write-Host and Write-Output

[edit | edit source]

When there are no other commands in the pipeline, Write-Host and Write-Output appear functionally identical. The difference is clear, however, when the pipeline is used. To provide the most functionality for future use and automation of PowerShell scripts, Write-Output is the preferred output cmdlet.[8] The Get-Date cmdlet may be used to demonstrate the difference between Write-Host and Write-Output.

# This script demonstrates the difference between Write-Host and Write-Output

Write-Host '1/1/01' | Get-Date      # Displays 1/1/01 (no pipeline content).
Write-Output '1/1/01' | Get-Date    # Displays the formatted date.
'1/1/01' | Get-Date                 # Displays the formatted date.

Activities

[edit | edit source]
  1. Review Microsoft TechNet: Using the Set-ExecutionPolicy Cmdlet. Change your local execution policy to RemoteSigned so that you can run your own local saved scripts.
  2. Review Microsoft TechNet: Using the Get-Alias Cmdlet. Display a list of all Windows PowerShell aliases.
  3. Review Microsoft TechNet: Using the Write-Host Cmdlet, Microsoft TechNet: Write-Output, and Microsoft TechNet: Using the Get-Date Cmdlet. Experiment with the different commands and the pipeline to ensure you understand the difference between Write-Host and Write-Output.
  4. Review Microsoft TechNet: Write-Output. Create a script that uses Write-Output to display your name. Try something like 'Hello Wikiversity!'. Add a comment at the top of the script that describes the purpose of the script. Then save the script as a file and experiment with running the script file using both PowerShell and PowerShell ISE.
  5. Review Microsoft TechNet: Using the Stop-Service Cmdlet and Microsoft TechNet: Using the Start-Service Cmdlet. Use Get-Service to get a list of running services. Then write a script that will stop and restart the Print Spooler service. Add a comment at the top of the script that describes the purpose of the script. Save the script as a file and experiment with running the script file using both PowerShell and PowerShell ISE.

Lesson Summary

[edit | edit source]
  • An integrated development environment (IDE) or interactive development environment is a software application that provides comprehensive facilities to computer programmers for software development.[9]
  • An IDE normally consists of a source code editor, build automation tools and a debugger.[10]
  • Most modern IDEs offer Intelligent code completion features.[11]
  • Automatic code completion in PowerShell and PowerShell ISE is accomplished using the <Tab> key.[12]
  • Cmdlet parameters are automatically listed by entering the dash or hyphen (-) character and then using the <Tab> key to cycle through the list.[13]
  • New PowerShell tabs are created using the File menu.[14]
  • Remote PowerShell tabs may be created to establish a session on a remote computer.[15]
  • The PowerShell ISE console executes commands when you press <Enter>.[16]
  • Multiple commands may be executed together in the PowerShell ISE console in sequence by separating them using <Shift>+<Enter>.[17]
  • To stop a command in PowerShell ISE, on the toolbar, click Stop Operation, or press <Ctrl>+<Break>.[18]
  • The default Windows PowerShell execution policy setting is Restricted.[19]
  • PowerShell ISE script breakpoints can be set using Toggle Breakpoint or by pressing the <F9> key.[20]
  • PowerShell profiles may be established by configuring a PowerShell script to run automatically when you start a new PowerShell or PowerShell ISE session.[21]
  • Saved PowerShell scripts are run using a full or relative path. The relative path for a PowerShell script in the current directory would be .\script.ps1.[22]
  • The Get-Alias cmdlet displays a list of current Windows PowerShell aliases.[23]
  • The Get-ExecutionPolicy cmdlet returns the current Windows PowerShell execution policy security level.[24]
  • The Set-ExecutionPolicy cmdlet sets the Windows PowerShell execution policy security level.[25]
  • The Start-Service cmdlet starts a stopped service or services.[26]
  • The Stop-Service cmdlet stops a running service or services.[27]
  • Starting and stopping services on Windows requires running PowerShell or the corresponding script as an administrator.
  • The Write-Host cmdlet writes directly to the host environment, bypassing the pipeline.[28]
  • The Write-Output cmdlet writes to the pipeline.[29]

Key Terms

[edit | edit source]
breakpoint
An intentional stopping or pausing place in a program, put in place for debugging purposes.[30]
debugging
A methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware, thus making it behave as expected.[31]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. An integrated development environment (IDE) or interactive development environment is a _____.
An integrated development environment (IDE) or interactive development environment is a software application that provides comprehensive facilities to computer programmers for software development.
2. An IDE normally consists of _____.
An IDE normally consists of a source code editor, build automation tools and a debugger.
3. Most modern IDEs offer _____.
Most modern IDEs offer Intelligent code completion features.
4. Automatic code completion in PowerShell and PowerShell ISE is accomplished using the _____ key.
Automatic code completion in PowerShell and PowerShell ISE is accomplished using the <Tab> key.
5. Cmdlet parameters are automatically listed by entering the _____ character and then using the _____ key to cycle through the list.
Cmdlet parameters are automatically listed by entering the dash or hyphen (-) character and then using the <Tab> key to cycle through the list.
6. New PowerShell tabs are created using the _____ menu.
New PowerShell tabs are created using the File menu.
7. Remote PowerShell tabs may be created to _____.
Remote PowerShell tabs may be created to establish a session on a remote computer.
8. The PowerShell ISE console executes commands when you press _____.
The PowerShell ISE console executes commands when you press <Enter>.
9. Multiple commands may be executed together in the PowerShell ISE console in sequence by separating them using _____.
Multiple commands may be executed together in the PowerShell ISE console in sequence by separating them using <Shift>+<Enter>.
10. To stop a command in PowerShell ISE, on the toolbar, click _____, or press _____.
To stop a command in PowerShell ISE, on the toolbar, click Stop Operation, or press <Ctrl>+<Break>.
11. The default Windows PowerShell execution policy setting is _____.
The default Windows PowerShell execution policy setting is Restricted.
12. PowerShell ISE script breakpoints can be set using _____ or by pressing the _____ key.
PowerShell ISE script breakpoints can be set using Toggle Breakpoint or by pressing the <F9> key.
13. PowerShell profiles may be established by _____.
PowerShell profiles may be established by configuring a PowerShell script to run automatically when you start a new PowerShell or PowerShell ISE session.
14. Saved PowerShell scripts are run using _____.
Saved PowerShell scripts are run using a full or relative path. The relative path for a PowerShell script in the current directory would be .\script.ps1.
15. The Get-Alias cmdlet _____.
The Get-Alias cmdlet displays a list of current Windows PowerShell aliases.
16. The Get-ExecutionPolicy cmdlet _____.
The Get-ExecutionPolicy cmdlet returns the current Windows PowerShell execution policy security level.
17. The Set-ExecutionPolicy cmdlet _____.
The Set-ExecutionPolicy cmdlet sets the Windows PowerShell execution policy security level.
18. The Start-Service cmdlet _____.
The Start-Service cmdlet starts a stopped service or services.
19. The Stop-Service cmdlet _____.
The Stop-Service cmdlet stops a running service or services.
20. Starting and stopping services on Windows requires _____.
Starting and stopping services on Windows requires running PowerShell or the corresponding script as an administrator.
21. The Write-Host cmdlet _____.
The Write-Host cmdlet writes directly to the host environment, bypassing the pipeline.
22. The Write-Output cmdlet _____.
The Write-Output cmdlet writes to the pipeline.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.
  1. Microsoft TechNet: Get-Alias
  2. Microsoft TechNet: Get-ExecutionPolicy
  3. Microsoft TechNet: Set-ExecutionPolicy
  4. Microsoft TechNet: Start-Service
  5. Microsoft TechNet: Stop-Service
  6. Microsoft TechNet: Write-Host
  7. Microsoft TechNet: Write-Output
  8. Jeffrey Snover's blog: Write-Host Considered Harmful
  9. Wikipedia: Integrated development environment
  10. Wikipedia: Integrated development environment
  11. Wikipedia: Integrated development environment
  12. Microsoft TechNet: How to Use Tab Completion
  13. Microsoft TechNet: How to Use Tab Completion
  14. Microsoft TechNet: How to Create a PowerShell Tab in Windows PowerShell ISE
  15. Microsoft TechNet: How to Create a PowerShell Tab in Windows PowerShell ISE
  16. Microsoft TechNet: How to Use the Console Pane in the Windows PowerShell ISE
  17. Microsoft TechNet: How to Use the Console Pane in the Windows PowerShell ISE
  18. Microsoft TechNet: How to Use the Console Pane in the Windows PowerShell ISE
  19. Microsoft TechNet: How to Write and Run Scripts in the Windows PowerShell ISE
  20. Microsoft TechNet: How to Debug Scripts in Windows PowerShell ISE
  21. Microsoft TechNet: How to Use Profiles in Windows PowerShell ISE
  22. PowerShell.com: Master-PowerShell | With Dr. Tobias Weltner - Chapter 2. Interactive PowerShell
  23. Microsoft TechNet: Get-Alias
  24. Microsoft TechNet: Get-ExecutionPolicy
  25. Microsoft TechNet: Set-ExecutionPolicy
  26. Microsoft TechNet: Start-Service
  27. Microsoft TechNet: Stop-Service
  28. Microsoft TechNet: Write-Host
  29. Microsoft TechNet: Write-Output
  30. Wikipedia: Breakpoint
  31. Wikipedia: Debugging

Lesson 4 - Variables

[edit | edit source]

This lesson introduces PowerShell variables, constants, and data types.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Explain basic concepts regarding variables.
  • Describe the difference between variables and constants.
  • Understand data types and type conversions.
  • Use variables to capture user input and use that input later in script output.

Readings

[edit | edit source]
  1. Wikipedia: Variable (computer science)
  2. Wikipedia: Constant (computer programming)
  3. Wikipedia: Data type
  4. Wikipedia: Type conversion
  5. Wikipedia: Scope (computer science)
  6. BonusBits: Mastering PowerShell Chapter 3 - Variables

Multimedia

[edit | edit source]
  1. YouTube: PowerShell - Working with Variables
  2. YouTube: PowerShell - How To - Variables

Examples

[edit | edit source]

Data Types

[edit | edit source]

PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.[1] The GetType method returns the current data type of the given variable.[2]

# This script demonstrates the difference between numeric and string data types.

$value = 1 + 1
$value                # Displays 2
$value.GetType()      # Displays Int32

$value = '1' + '1'
$value                # Displays 11
$value.GetType()      # Displays String

Type Conversion

[edit | edit source]

Variables may be cast from one type to another by explicit conversion.

# This script demonstrates data types and data type conversion.

$value = 1.9

$value              # Displays 1.9
[int32]$value       # Displays 2
[float]$value       # Displays 1.9
[string]$value      # Displays 1.9
[boolean]$value     # Displays True
[datetime]$value    # Displays January 9 ...

Quotes

[edit | edit source]

Single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.[3]

# This script demonstrates the difference between single quotes and double quotes.

$single = '$(1 + 2)'
$double = "$(1 + 2)"

Write-Output $single    # Displays $(1 + 2)
Write-Output $double    # Displays 3

Read-Host

[edit | edit source]

The Read-Host cmdlet reads a line of input from the console.[4] Following is an example of a script that requests input from the user and then uses that input to generate the output. Note the use of both single and double quotes for string processing.

# This script displays a message based on user input.

$myinput = Read-Host 'Is it morning, afternoon, or evening? '
Write-Output "Good $myinput!"

Activities

[edit | edit source]
  1. Review Microsoft TechNet: Get-Variable and Microsoft TechNet: about_Automatic_Variables. Start a new PowerShell session and use Get-Variable to display a list of all automatic variables and values that are defined by default when a new session is started.
  2. Review Microsoft TechNet: Using the Read-Host Cmdlet. Write a script that asks the user to enter their name, and then display a greeting back to the user that includes their name, such as 'Hello Wikiversity!'. Add a comment at the top of the script that describes the purpose of the script.
  3. Review Microsoft TechNet: about_Quoting_Rules. Experiment with the Hello script above using both using single quotes and double quotes to display the strings to ensure that you understand the difference between the two.
  4. Review Windows IT Pro: Working with PowerShell's Data Types. Experiment with entering different types of data (integers, floating point values, dates, strings) and use GetType() to display the data type entered.
  5. Review PowerShell.cz: Explicit Type Casting Versus Strongly Typed Variables. Experiment with data type conversion (type casting) and strongly typed variables when entering different types of data.

Lesson Summary

[edit | edit source]
  • A variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.[5]
  • A constant is an identifier whose associated value cannot typically be altered by the program during its execution.[6]
  • Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.[7]
  • In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters.[8]
  • A data type or simply type is a classification identifying one of various types of data, such as real, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.[9]
  • Type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.[10]
  • The scope of a variable describes where in a program's text the variable may be used, while the extent (or lifetime) describes when in a program's execution a variable has a (meaningful) value.[11]
  • Scope can vary from as little as a single expression to as much as the entire program, with many possible gradations -- such as code block, function, or module -- in between. [12]
  • In PowerShell, a variable name always begins with a dollar sign ($).[13]
  • PowerShell variable names are not case sensitive.[14]
  • The assignment operator (=) sets a variable to a specified value. You can assign almost anything to a variable, even complete command results.[15]
  • PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.
  • Variables may be converted from one type to another by explicit conversion, such as [int32]$value.
  • In Windows PowerShell, single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.[16]
  • The Read-Host cmdlet reads a line of input from the console.[17]

Key Terms

[edit | edit source]
ASCII (American Standard Code for Information Interchange)
A character-encoding scheme originally based on the English alphabet that encodes 128 specified characters - the numbers 0-9, the letters a-z and A-Z, some basic punctuation symbols, some control codes that originated with Teletype machines, and a blank space - into 7-bit binary integers.[18]
bit
A binary digit, having only two possible values most commonly represented as 0 and 1.[19]
Boolean
A data type with only two possible values: true or false.[20]
byte
A unit of digital information in computing and telecommunications that most commonly consists of eight bits, representing the values 0 through 255.[21]
character
A unit of information that roughly corresponds to a symbol , such as in an alphabet in the written form of a natural language.[22]
floating-point
A method of representing an approximation of a real number in a way that can support a wide range of values based on a fixed number of significant digits which are scaled using an exponent.[23]
garbage collection
A form of automatic memory management in which the garbage collector attempts to reclaim memory occupied by objects that are no longer in use by the program.[24]
immutable
An object whose state or value cannot be modified after it is created.[25]
integer
A data type which represents some finite subset of whole numbers, such as -32,768 to 32,767.[26][27]
memory leak
Incorrect management of memory allocation by a program, resulting in a reduction of available memory for running applications.[28]
string
A data type which represents a sequence of characters, either as a literal constant or as some kind of variable.[29]
Unicode
A computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems, in which a single character may be represented by one, two, or four bytes, depending on the character set and encoding used.[30]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. A variable or scalar is _____.
A variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.
2. A constant is _____.
A constant is an identifier whose associated value cannot typically be altered by the program during its execution.
3. Many programming languages employ a reserved value (often named _____) to indicate an invalid or uninitialized variable.
Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.
4. In almost all languages, variable names cannot start with _____ and cannot contain _____.
In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters.
5. A data type or simply type is _____ that determines _____, _____, _____, and _____.
A data type or simply type is a classification identifying one of various types of data, such as real, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.
6. Type conversion, typecasting, and coercion are _____.
Type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.
7. The scope of a variable describes _____, while the extent (or lifetime) describes _____.
The scope of a variable describes where in a program's text the variable may be used, while the extent (or lifetime) describes when in a program's execution a variable has a (meaningful) value.
8. Scope can vary from as little as _____ to as much as _____, with many possible gradations -- such as _____ in between.
Scope can vary from as little as a single expression to as much as the entire program, with many possible gradations -- such as code block, function, or module -- in between.
9. In PowerShell, a variable name always begins with _____.
In PowerShell, a variable name always begins with a dollar sign ($).
10. PowerShell variable names _____ case sensitive.
PowerShell variable names are not case sensitive.
11. The assignment operator _____. You can assign almost anything to a variable, even _____.
The assignment operator (=) sets a variable to a specified value. You can assign almost anything to a variable, even complete command results.
12. PowerShell data types include _____.
PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.
13. Variables may be converted from one type to another by _____.
Variables may be converted from one type to another by explicit conversion, such as [int32]$value.
14. In Windows PowerShell, single quotes display literal strings _____. Double quotes _____.
In Windows PowerShell, single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.
15. The Read-Host cmdlet _____.
The Read-Host cmdlet reads a line of input from the console.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 5 - Expressions

[edit | edit source]

This lesson introduces PowerShell expressions.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe the operators used in PowerShell scripts.
  • Explain order of operation.
  • Create PowerShell scripts to perform calculations based on user input.

Readings

[edit | edit source]
  1. Wikipedia: Expression (computer science)
  2. Wikipedia: Statement (computer science)
  3. Wikipedia: Order of operations
  4. Wikipedia: Unary operation
  5. Microsoft TechNet: about_Operators

Multimedia

[edit | edit source]
  1. YouTube: Windows PowerShell Fundamentals Chapter 14 - More Operators
  2. YouTube: PowerShell - How To - Operators

Examples

[edit | edit source]

Arithmetic Operators

[edit | edit source]

Arithmetic operators calculate values.[1]

$a = 3
$b = 2

$a + $b    # 5
$a - $b    # 1
$a * $b    # 6
$a / $b    # 1.5
$a % $b    # 1
-$a        # -3

Assignment Operators

[edit | edit source]

Assignment operators assign calculated values to variables.[2]

$a = 3
$b = 2

$a += $b    # a = 5
$a -= $b    # a = 3
$a *= $b    # a = 6
$a /= $b    # a = 3
$a %= $b    # a = 1

Unary Operators

[edit | edit source]

Unary operators increment or decrement a single variable by one.[3]

$a = 1

$a++    # a = 2
$a--    # a = 1

Comparison Operators

[edit | edit source]

Comparison operators compare values and test conditions.[4]

$a = 3
$b = 2

$a -eq $b    # False
$a -ne $b    # True
$a -lt $b    # False
$a -gt $b    # True
$a -le $b    # False
$a -ge $b    # True

Logical Operators

[edit | edit source]

Logical operators compare complex conditions.[5]

$a = 3
$b = 2

$a -lt $b -and $b -lt $a    # False
$a -lt $b -or $b -lt $a     # True
$a -lt $b                   # False
-not ($a -lt $b)            # True

String Operators

[edit | edit source]

String operators split, join, and concatenate substrings.[6]

$a = 'Cat,Dog,Fish,Hamster'
$a -split ','                           # Cat
                                        # Dog
                                        # Fish
                                        # Hamster

$b = @('Cat','Dog','Fish','Hamster')
$b -join ','                            # Cat,Dog,Fish,Hamster

'Cat' + 'Dog' + 'Fish' + 'Hamster'      # CatDogFishHamster

Activities

[edit | edit source]
  1. Review Microsoft TechNet: about_Operators. Experiment with different arithmetic operators to ensure you understand how they work. Then review Microsoft TechNet: about_Operator_Precedence and MathsIsFun: Order of Operations. Create a script that demonstrates the order of operations for PowerShell operators.
  2. Create a script that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds.
  3. Review MathsIsFun: Conversion of Temperature. Create a script that asks the user for a Fahrenheit temperature and then calculate and display the corresponding Celsius temperature or ask the user for a Celsius temperature and then calculate and display the corresponding Fahrenheit temperature.
  4. Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes.

Lesson Summary

[edit | edit source]
  • An expression is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value.[7]
  • A statement is the smallest standalone element of an imperative programming language which expresses some action to be carried out.[8]
  • In most languages, statements contrast with expressions in that statements do not return results and are executed solely for their side effects, while expressions always return a result and often do not have side effects at all.[9]
  • The order of operations (sometimes called operator precedence) is a rule used to clarify which procedures should be performed first in a given mathematical expression.[10]
  • The order of operations is exponents and roots, followed by multiplication and division, followed by addition and subtraction.[11]
  • Parentheses are used to explicitly denote precedence by grouping parts of an expression that should be evaluated first.[12]
  • The mnemonic PEMDAS may be used to recall the order of operations of Parentheses, Exponents, Multiplication, Division, Addition, Subtraction.[13]
  • A unary operation is an operation with only one operand.[14]
  • Arithmetic operators calculate values.[15]
  • Assignment operators assign calculated values to variables.[16]
  • Unary operators increment or decrement a single variable by one.[17]
  • Comparison operators compare values and test conditions.[18]
  • Logical operators compare complex conditions.[19]
  • String operators split, join, and concatenate substrings.[20]
  • +, -, *, /, and % are the addition subtraction, multiplication, division, and modulus (remainder) operators.[21]
  • =, +=, -=, *=, /=, and %= are the assignment operators.[22]
  • ++ and -- are the unary increment and decrement operators.[23]
  • -eq, -ne, -gt, -lt, -le, and -ge are the equal, not equal, greater than, less than, less than or equal, and greater than or equal comparison operators.[24]
  • -and, -or, -xor, and -not or ! are the and, or, exclusive or, and negation logical operators.[25]
  • -split and -join are the string operators.[26]

Key Terms

[edit | edit source]
identifier
A name that identifies (that is, labels the identity of) either a unique object or a unique class of objects.[27]
modulo (sometimes called modulus)
The operation that finds the remainder of division of one number by another.[28]
reserved word
A word that cannot be used as an identifier, such as the name of a variable, function, or label.[29]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. An expression is _____.
An expression is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value.
2. A statement is _____.
A statement is the smallest standalone element of an imperative programming language which expresses some action to be carried out.
3. In most languages, statements contrast with expressions in that statements _____, while expressions _____.
In most languages, statements contrast with expressions in that statements do not return results and are executed solely for their side effects, while expressions always return a result and often do not have side effects at all.
4. The order of operations (sometimes called operator precedence) is a rule used to _____.
The order of operations (sometimes called operator precedence) is a rule used to clarify which procedures should be performed first in a given mathematical expression.
5. The order of operations is _____.
The order of operations is exponents and roots, followed by multiplication and division, followed by addition and subtraction.
6. Parentheses are used to _____.
Parentheses are used to explicitly denote precedence by grouping parts of an expression that should be evaluated first.
7. The mnemonic PEMDAS may be used to _____.
The mnemonic PEMDAS may be used to recall the order of operations of Parentheses, Exponents, Multiplication, Division, Addition, Subtraction.
8. A unary operation is _____.
A unary operation is an operation with only one operand.
9. Arithmetic operators _____.
Arithmetic operators calculate values.
10. Assignment operators _____.
Assignment operators assign calculated values to variables.
11. Unary operators _____.
Unary operators increment or decrement a single variable by one.
12. Comparison operators _____.
Comparison operators compare values and test conditions.
13. Logical operators _____.
Logical operators compare complex conditions.
14. String operators _____.
String operators split, join, and concatenate substrings.
15. +, -, *, /, and % are _____.
+, -, *, /, and % are the addition subtraction, multiplication, division, and modulus (remainder) operators.
17. ++ and -- are _____.
++ and -- are the unary increment and decrement operators.
18. -eq, -ne, -gt, -lt, -le, and -ge are _____.
-eq, -ne, -gt, -lt, -le, and -ge are the equal, not equal, greater than, less than, less than or equal, and greater than or equal comparison operators.
19. -and, -or, -xor, and -not or ! are _____.
-and, -or, -xor, and -not or ! are the and, or, exclusive or, and negation logical operators.
20. -split and -join are _____.
-split and -join are string operators.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 6 - Conditions

[edit | edit source]

This lesson introduces PowerShell conditions, switch statements, and regular expressions.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic conditional statement concepts.
  • Create PowerShell scripts that use if statements.
  • Create PowerShell scripts that use switch statements.

Readings

[edit | edit source]
  1. Wikipedia: Conditional (computer programming)
  2. Wikipedia: Switch statement
  3. Wikipedia: Regular expression
  4. BonusBits: Mastering PowerShell Chapter 7 - Conditions

Multimedia

[edit | edit source]
  1. YouTube: Powershell: Learn How to Use If/Then/Else
  2. YouTube: Switch
  3. YouTube: PowerShell - How To - If Statement

Examples

[edit | edit source]

The if statement runs code blocks based on the results of one or more conditional tests.[1]

$tp= Read-Host 'Is it Morning (M), Afternoon (A), or Evening (E)? '
if($tp -eq 'm')
{
    Write-Output 'Good morning!'
}
elseif($tp -eq 'a')
{
    Write-Output 'Good afternoon!'
}
elseif($tp -eq 'e')
{
    Write-Output 'Good evening!'
}
else
{
    Write-Output 'Hello!'
}

Switch

[edit | edit source]

The switch statement checks multiple conditions for a given value and runs the corresponding code blocks.[2]

$tp = Read-Host 'Is it Morning (M), Afternoon (A), or Evening (E)? '
switch($tp)
{
    m {'Good morning!'}
    a {'Good afternoon!'}
    e {'Good evening!'}
    default {'Hello!'}
}

-Match

[edit | edit source]

The -match operator is used to match regular expressions. For example:[3]

$zipcode = Read-Host 'Enter zip code'
if(!($zipcode -match '^\d{5}(-\d{4})?$'))
{
    Write-Output "$zipcode is not a valid zip code."
}

Switch -Regex

[edit | edit source]

The switch -Regex statement checks multiple conditions for a given value based on regular expression matching and runs the corresponding code blocks.[4]

$x = Read-Host 'Enter something'
switch -Regex ($x)
{
    '.'   {'You entered a character'}
    '\d'  {'You entered a digit'}
    '\s'  {'You entered a space'}
    '\w'  {'You entered a word'}
    '\w \w' {'You entered multiple words'}
    default {'You entered nothing'}
}

Break

[edit | edit source]

The break statement immediately exits the nearest enclosing Foreach, For, While, Do, or Switch statement.[5]

$x= Read-Host 'Enter something'
switch -Regex ($x)
{
    '^.$'
    {
        'You entered a character'
        break
    }

    '^\d$'
    {
        'You entered a digit'
        break
    }

    '^\s$'
    {
        'You entered a space'
        break
    }

    '\w \w'
    {
        'You entered multiple words'
        break
    }

    '\w'
    {
        'You entered a word'
        break
    }

    default
    {
        'You entered nothing'
    }
}

Activities

[edit | edit source]
  1. Review Microsoft Developer Network: Boolean Values and Operators. Create a script that uses different values and conditions to confirm that in PowerShell zero is false and anything non-zero is true. Also show that the explicit value of $false is 0 and the explicit value of $true is 1.
  2. Create a script that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use an if/elseif/else statement to display their approximate age in the selected timeframe.
  3. Review MathsIsFun: Conversion of Temperature. Create a script that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use an if/elseif/else statement to determine their selection and then gather the appropriate input and calculate and display the converted temperature.
  4. Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user what shape they would like to calculate the area for. Use an if/elseif/else statement to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  5. Create a script that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a switch statement to display their approximate age in the selected timeframe.
  6. Review MathsIsFun: Conversion of Temperature. Create a script that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a switch statement to determine their selection and then gather the appropriate input and calculate and display the converted temperature.
  7. Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user what shape they would like to calculate the area for. Use a switch statement to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  8. Review Regular-Expressions: How to Find or Validate an Email Address. Create a script that uses the -match operator and a regular expression to test user input email addresses.

Lesson Summary

[edit | edit source]
  • Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.[6]
  • The pseudocode structure of a conditional statement is:[7]
IF (boolean condition) THEN
    (consequent)
ELSE
    (alternative)
END IF
  • If the condition is true, the statements following the THEN are executed. Otherwise, the execution continues in the following branch – either in the ELSE block (which is usually optional), or if there is no ELSE branch, then after the END IF.[8]
  • By using ELSE IF/ELSEIF, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.[9]
  • The PowerShell syntax for a conditional statement is:[10]
if (<test1>)
    {<statement list 1>}
elseif (<test2>)
    {<statement list 2>}
else
    {<statement list 3>}
  • In PowerShell conditions, the elseif and else statements are optional.[11]
  • By default, all comparison operators (-eq, -lt, -gt, etc.) are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a "c" (-ceq, -clt, -cgt, etc.).[12]
  • In PowerShell, zero is false and anything non-zero is true. When evaluated explicitly, $false is 0 and $true is 1.[13]
  • A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.[14]
  • Switch statements come in two main variants: a structured switch which takes exactly one branch, and an unstructured switch which functions as a type of GOTO.[15]
  • PowerShell switch statements function as a hybrid between structured and unstructured, where every condition in the switch is evaluated, even after a match, but only the code block immediately following any matching condition is executed.[16]
  • The PowerShell syntax for a switch statement is:[17]
switch (<test-value>)
{
    <condition> {<statement list 1>}
    <condition> {<statement list 2>}
    ...
    default {<statement list 3>}
}
  • In PowerShell switch statements, the default case is optional.[18]
  • The break statement immediately exits the nearest enclosing Foreach, For, While, Do, or Switch statement.[19]
  • A regular expression (abbreviated regex) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings.[20]
  • Each character in a regular expression is either understood to be a metacharacter with its special meaning, or a regular character with its literal meaning.[21]
  • In regex, | indicates either|or.[22]
  • In regex, ? indicates there is zero or one of the preceding element.[23]
  • In regex, * indicates there is zero or more of the preceding element.[24]
  • In regex, + indicates there is one or more of the preceding element.[25]
  • In regex, () is used to group elements.[26]
  • In regex, . matches any single character.[27]
  • In regex, [] matches any single character contained within the brackets.[28]
  • In regex, [^] matches any single character not contained within the brackets.[29]
  • In regex, ^ matches the start of the string.[30]
  • In regex, $ matches the end of the string.[31]
  • In regex, \w matches a word.[32]
  • In regex, \d matches a digit.[33]
  • In regex, \s matches whitespace.[34]

Key Terms

[edit | edit source]
Spaghetti code
a pejorative term for source code that has a complex and tangled control structure, especially one using many GOTO statements, exceptions, threads, or other unstructured branching constructs.[35]
Structured programming
A programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures and for and while loops.[36]
Whitespace
Any character or series of characters that represent horizontal or vertical space.[37]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Conditional statements are _____.
Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.
2. The pseudocode structure of a conditional statement is:
The pseudocode structure of a conditional statement is:
IF (boolean condition) THEN
  (consequent)
ELSE
  (alternative)
END IF
3. If the condition is true, _____. Otherwise, the execution continues in _____.
If the condition is true, the statements following the THEN are executed. Otherwise, the execution continues in the following branch – either in the ELSE block (which is usually optional), or if there is no ELSE branch, then after the END IF.
4. By using ELSE IF/ELSEIF, it is possible to _____
By using ELSE IF/ELSEIF, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.
5. The PowerShell syntax for a conditional statement is:
The PowerShell syntax for a conditional statement is:
if (<test1>)
  {<statement list 1>}
elseif (<test2>)
  {<statement list 2>}
else
  {<statement list 3>}
6. In PowerShell conditions, the elseif and else statements are _____.
In PowerShell conditions, the elseif and else statements are optional.
7. By default, all comparison operators (-eq, -lt, -gt, etc.) are case-_____. To make a comparison operator case-_____, _____.
By default, all comparison operators (-eq, -lt, -gt, etc.) are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a "c" (-ceq, -clt, -cgt, etc.).
8. In PowerShell, zero is _____ and anything non-zero is _____. When evaluated explicitly, $false is _____ and $true is _____.
In PowerShell, zero is false and anything non-zero is true. When evaluated explicitly, $false is 0 and $true is 1.
9. A switch statement is a _____
A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.
10. Switch statements come in two main variants: _____, and _____.
Switch statements come in two main variants: a structured switch which takes exactly one branch, and an unstructured switch which functions as a type of GOTO.
11. PowerShell switch statements function as a hybrid between structured and unstructured, where _____.
PowerShell switch statements function as a hybrid between structured and unstructured, where every condition in the switch is evaluated, even after a match, but only the code block immediately following any matching condition is executed.
12. The PowerShell syntax for a switch statement is:
The PowerShell syntax for a switch statement is:
switch (<test-value>)
{
  <condition> {<statement list 1>}
  <condition> {<statement list 2>}
  ...
  default {<statement list 3>}
}
13. In PowerShell switch statements, _____ is optional.
In PowerShell switch statements, the default case is optional.
14. The break statement _____.
The break statement immediately exits the nearest enclosing Foreach, For, While, Do, or Switch statement.
15. A regular expression (abbreviated regex) is _____.
A regular expression (abbreviated regex) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings.
16. Each character in a regular expression is either understood to be a _____, or a _____.
Each character in a regular expression is either understood to be a metacharacter with its special meaning, or a regular character with its literal meaning.
17. In regex, | indicates _____.
In regex, | indicates either|or.
18. In regex, ? indicates _____.
In regex, ? indicates there is zero or one of the preceding element.
19. In regex, * indicates _____.
In regex, * indicates there is zero or more of the preceding element.
20. In regex, + indicates _____.
In regex, + indicates there is one or more of the preceding element.
21. In regex, () is used to _____.
In regex, () is used to group elements.
22. In regex, . matches _____.
In regex, . matches any single character.
23. In regex, [] matches _____.
In regex, [] matches any single character contained within the brackets.
24. In regex, [^] matches _____.
In regex, [^] matches any single character not contained within the brackets.
25. In regex, ^ matches _____.
In regex, ^ matches the start of the string.
26. In regex, $ matches _____.
In regex, $ matches the end of the string.
27. In regex, \w matches _____.
In regex, \w matches a word.
28. In regex, \d matches _____.
In regex, \d matches a digit.
29. In regex, \s matches _____.
In regex, \s matches whitespace.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 7 - Loops

[edit | edit source]

This lesson introduces PowerShell loops, including condition-based while and do while/do until loops, counter-based for loops, and collection-based foreach loops.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic loop statement concepts.
  • Create PowerShell scripts that use while and do loops.
  • Create PowerShell scripts that use for loops.
  • Create PowerShell scripts using foreach loops.

Readings

[edit | edit source]
  1. Wikipedia: Control flow
  2. BonusBits: Mastering PowerShell Chapter 8 - Loops

Multimedia

[edit | edit source]
  1. YouTube: PowerShell For Loops
  2. YouTube: Do While Loops in PowerShell
  3. YouTube: ForEach Loops in PowerShell
  4. YouTube: PowerShell Loops
  5. YouTube: PowerShell - How To - Loops

Examples

[edit | edit source]

While

[edit | edit source]

The while statement runs a statement list zero or more times based on the results of a conditional test.[1]

$i = 0
while($i -lt 3)
{
    Write-Output $i
    $i++
}

Do While

[edit | edit source]

The do while statement runs a statement list one or more times based on the affirmative results of a conditional test.[2]

$i = 0
do
{
    Write-Output $i
    $i++
}while($i -lt 3)

It is important to note that, unlike while, a do while or do until will always execute at least once.

$i = 0
do
{
    Write-Output $i
    $i--
}while($i -gt 0)

Do Until

[edit | edit source]

The do until statement runs a statement list one or more times based on the negative results of a conditional test.[3]

$i = 0
do
{
    Write-Output $i
    $i++
}until($i -ge 3)

The for statement runs a statement list zero or more times based on an initial setting, a conditional test, and a repeated statement, most often used with numeric counters.[4]

for($i = 0; $i -lt 11; $i++)
{
    Write-Output $i
}

For loops are often nested to repeat actions, such as for rows and columns. For example:

for($i = 0; $i -lt 3; $i++)
{
    $line = ''
    for($j = 0; $j -lt 3; $j++)
    {
        $line += $i.ToString() + $j.ToString() + '  '
    }
    Write-Output $line
}

ForEach

[edit | edit source]

The foreach statement runs a statement list once for each item in a collection.[5]

$processes = Get-Process
foreach($process in $processes)
{
    if($process.PM / 1024 / 1024 -gt 100)
    {
        Write-Output ('Process ' + $process.Name + ' is using more than 100 MB RAM.')
    }
}

Continue

[edit | edit source]

The continue statement immediately returns script flow to the top of the innermost While, Do, For, or ForEach loop.[6]

$processes = Get-Process
foreach($process in $processes)
{
    if($process.PM / 1024 / 1024 -le 100)
    {
        continue
    }
    Write-Output ('Process ' + $process.Name + ' is using more than 100 MB RAM.')
}

Break

[edit | edit source]

The break statement causes Windows PowerShell to immediately exit the innermost While, Do, For, or ForEach loop or Switch code block.[7]

$processes = Get-Process
foreach($process in $processes)
{
    if($process.PM / 1024 / 1024 -gt 100)
    {
        Write-Output ('Process ' + $process.Name + ' is using more than 100 MB RAM.')
        break
    }
}

Exit causes Windows PowerShell to exit a script or a Windows PowerShell instance.[8]

if(<some fatal error>)
{
    Exit <optional return code>
}

Foreach-Object

[edit | edit source]

The ForEach-Object cmdlet runs a command list once for each item in a collection.[9] While the ForEach-Object cmdlet is often more convenient, the foreach statement and a coded loop usually offers better performance.

Get-Process | ForEach-Object { if($_.PM / 1024 / 1024 -gt 100) {'Process ' + $_.Name + ' is using more than 100 MB RAM.'} }

Start-Sleep

[edit | edit source]

The Start-Sleep cmdlet allows you to pause Windows PowerShell activity for a specified period of time.[10] It is particularly useful with long-running scripts or infinite loops.

while($true)
{
    if((Get-Date -Format 'hh:mm') -eq '00:00')
    {
        'It''s midnight.  You should go to sleep.'
    }
    Start-Sleep -Seconds 60
}

Get-Counter

[edit | edit source]

The Get-Counter cmdlet gets performance counter data from local and remote computers.[11]

Get-Counter

Activities

[edit | edit source]
  1. Create a script that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores. Revise the script several times to compare the code required when the loop control structure is based on while, do while, do until, and for statements, respectively.
  2. Review MathsIsFun: 10x Printable Multiplication Table. Create a script that uses nested for loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values.
  3. Review MathsIsFun: 10x Printable Multiplication Table. Create a script that uses nested for loops to generate a multiplication table. Use a condition with (<variable> % 2) to test for odd or even values. Generate the multiplication table only for even values. For odd values, use the continue statement to continue the next iteration of the loop.
  4. Review MathsIsFun: 10x Printable Multiplication Table. Create a script that uses nested for loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Use a break statement to terminate the loop if the count exceeds 10.
  5. Create a script that retrieves a list of all services and then uses foreach to display the names of all running services. While this could also be done using Select-Object, there are times when processing objects is faster and easier using foreach.
  6. Review Microsoft TechNet: Using the Start-Sleep Cmdlet. Write a script that uses an infinite loop to call the Get-Counter cmdlet every sixty seconds. Redirect the Get-Counter output and append it to a file. Run the script for a few minutes and then check the file contents to observe system utilization.

Lesson Summary

[edit | edit source]
  • Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.[12]
  • Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.[13]
  • PowerShell does not support an unconditional branch. All control flow must be structured using conditions, loops, functions (subroutines), or exit (unconditional halt).
  • PowerShell uses curly braces to designate code blocks and control structures.[14]
  • A loop is a sequence of statements which is specified once but which may be carried out several times in succession.[15]
  • Loop structures include while and do while/do until, for, and foreach.[16]
  • While and do while/do until are condition-controlled loops, repeating until some condition changes.[17]
  • For loops are count-controlled loops, repeating a certain number of times.[18]
  • Foreach loops are collection-controlled loops repeating for all elements of an array, or all members of a set or collection.[19]
  • Loops may be continued prematurely using the continue statement.[20]
  • Loops may be terminated prematurely using the break statement.[21]
  • Scripts may be terminated prematurely using the exit statement.[22]
  • The ForEach-Object cmdlet runs a command list once for each item in a collection.[23]
  • The Start-Sleep cmdlet allows you to pause Windows PowerShell activity for a specified period of time.[24]
  • The Get-Counter cmdlet gets performance counter data from local and remote computers.[25]

Key Terms

[edit | edit source]
infinite loop
A sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.[26]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Control flow refers to _____.
Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.
2. Control flow statement types include _____, _____, _____, _____, and _____.
Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.
3. PowerShell does not support _____. All control flow must be structured using _____, _____, _____, or _____.
PowerShell does not support an unconditional branch. All control flow must be structured using conditions, loops, functions (subroutines), or exit (unconditional halt).
4. PowerShell uses curly braces to _____.
PowerShell uses curly braces to designate code blocks and control structures.
5. A loop is _____.
A loop is a sequence of statements which is specified once but which may be carried out several times in succession.
6. Loop structures include _____ and _____, _____, and _____.
Loop structures include while and do while/do until, for, and foreach.
7. While and do while/do until are _____.
While and do while/do until are condition-controlled loops, repeating until some condition changes.
8. For loops are _____.
For loops are count-controlled loops, repeating a certain number of times.
9. Foreach loops are _____.
Foreach loops are collection-controlled loops repeating for all elements of an array, or all members of a set or collection.
10. Loops may be continued prematurely using _____.
Loops may be continued prematurely using the continue statement.
11. Loops may be terminated prematurely using _____.
Loops may be terminated prematurely using the break statement.
12. Scripts may be terminated prematurely using _____.
Scripts may be terminated prematurely using the exit statement.
13. The ForEach-Object cmdlet _____.
The ForEach-Object cmdlet runs a command list once for each item in a collection.
14. The Start-Sleep cmdlet _____.
The Start-Sleep cmdlet allows you to pause Windows PowerShell activity for a specified period of time.
15. The Get-Counter cmdlet _____.
The Get-Counter cmdlet gets performance counter data from local and remote computers.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 8 - Arrays

[edit | edit source]

This lesson introduces PowerShell arrays and hash tables.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic array and hash table concepts
  • Create PowerShell scripts that use arrays.
  • Create PowerShell scripts that use hash tables.

Readings

[edit | edit source]
  1. Wikipedia: Array data type
  2. Wikipedia: Associative array
  3. BonusBits: Mastering PowerShell Chapter 4 - Arrays and Hashtables

Multimedia

[edit | edit source]
  1. YouTube: Arrays

Examples

[edit | edit source]

Initializing an Array

[edit | edit source]
$array=@(1,2,3,5,6,7,8);

Checking the Size of an Array

[edit | edit source]
$array.Length

Accessing Array Elements

[edit | edit source]
$array[0] + $array[1] + $array[2]

Initializing an Empty Array

[edit | edit source]
$array = @()

Adding Elements to an Array

[edit | edit source]
$array += 1
$array += 2
$array += 3

Removing Elements from an Array

[edit | edit source]

To remove the elements which are not required in an array, use the below command. This stores only the sub-arrays mentioned here.

$array = @($array[0], $array[2])

Looping Through an Array Using a For Loop

[edit | edit source]
for($i = 0; $i -lt $array.Length; $i++)
{
    $array[$i]
}

Looping Through an Array Using a ForEach Loop

[edit | edit source]
foreach($element in $array)
{
    $element
}

Multi-Dimensional Arrays

[edit | edit source]
$array = @(1, 2, 3), @(4, 5, 6), @(7, 8, 9)

$array[0]    # 1
             # 2
             # 3

$array[0][0]  # 1

$array[2][2]  # 9

Initializing a Hash Table

[edit | edit source]
$pets = @{Cat = 'Frisky'; Dog = 'Spot'; Fish = 'Nimo'; Hamster = 'Whiskers'}

Accessing Hash Table Items

[edit | edit source]
$pets.Cat    # Frisky
$pets.Dog    # Spot
$pets.Fish    # Nimo
$pets.Hamster  # Whiskers

Initializing an Empty Hash Table

[edit | edit source]
$pets = @{}

Adding Items to a Hash Table

[edit | edit source]

Either:

$pets.Add('Cat', 'Frisky')
$pets.Add('Dog', 'Spot')
$pets.Add('Fish', 'Nimo')
$pets.Add('Hamster', 'Whiskers')

or:

$pets.Cat = 'Frisky'
$pets.Dog = 'Spot'
$pets.Fish = 'Nimo'
$pets.Hamster = 'Whiskers'

Removing Items from a Hash Table

[edit | edit source]
$pets.Remove('Hamster')

Looping Through a Hash Table Using ForEach

[edit | edit source]
foreach($pet in $pets.keys)
{
    $pet # Print each Key
    $pets.$pet # Print value of each Key
}

Format-Table

[edit | edit source]

The Format-Table cmdlet formats hash table output as a table.[1]

$pets | Format-Table

Format-List

[edit | edit source]

The Format-List cmdlet formats hash table output as a list of separate key-value pairs.[2]

$pets | Format-List

Activities

[edit | edit source]
  1. Review Microsoft TechNet: about_Arrays. Create a script that initializes an array with the names of all of the members of your family. Use Sort-Object to sort and display the names.
  2. Review Microsoft TechNet: about_Arrays. Create a script that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a for or while loop to store each score in an array. Finally, use a for or foreach loop to calculate and display the average for the entered scores.
  3. Review Microsoft TechNet: Working with Hash Tables Create a script that initializes a hash table with the names of all of the members of your family. Use Sort-Object and Format-Table to sort and display the names.
  4. As above, create a script that uses a hash table to hold the names of all of the members of your family and use Sort-Object to sort and display the names. This time, start by initializing an empty hash table, and add each name to the hash table as it is entered by the user. Use Sort-Object and Format-List to sort and display the names.
  5. Review Microsoft TechNet: about_Hash_Tables. Create a script that asks the user to enter their name, address, city, state, and postal code. Store each entry as an item in a hash table. Display the name and address information as you would for a printed mailing address.

Lesson Summary

[edit | edit source]
  • An array is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time by the program.[3]
  • Arrays are distinguished from lists in that arrays allow random access, while lists only allow sequential access. This feature allows a single iterative statement to process arbitrarily many elements of an array variable.[4]
  • An index is a value, typically a numeric integer, used to identify and reference an array element.[5]
  • Array indexes start at either zero or one, depending on the programming language, and correspondingly end at either the number of elements minus one [0..n-1] or at the number of elements [1..n].[6] PowerShell arrays are zero-based.
  • The number of indices needed to specify an element is called the dimension, dimensionality, or rank of the array type.[7]
  • Dynamic arrays are resizable and may be expanded at any time after creation, without changing the values of the current elements.[8]
  • Index checking means that, in all expressions indexing an array, the index value is checked against the bounds of the array (which were established when the array was defined), and if the index is out-of-bounds, further execution is suspended via some sort of error.[9]
  • A hash table is a data structure used to implement an associative array, a structure that can map keys to values.[10]
  • A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.[11]
  • An associative array is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.[12]
  • PowerShell arrays are initialized using @(value, value) syntax.[13]
  • PowerShell array elements are accessed using $array[element] syntax.[14]
  • An empty PowerShell array is created using @().[15]
  • PowerShell array elements are added using $array += element syntax.[16]
  • PowerShell array elements are removed using $array = $array[sub..set] + $array[sub..set] syntax.[17]
  • PowerShell multi-dimensional array elements are accessed using $array[element][element] syntax.[18]
  • PowerShell hash tables are initialized using @{key = value; key = value} syntax.[19]
  • Hash table values are accessed using $table.key syntax.[20]
  • An empty PowerShell hash table is created using @{}.[21]
  • PowerShell hash table values are added using $table.Add(key, value) syntax or $table.key = value syntax.[22]
  • PowerShell hash table values are removed using $table.Remove(key) syntax.[23]
  • The Format-Table cmdlet formats hash table output as a table.[24]
  • The Format-List cmdlet formats hash table output as a list of separate key-value pairs.[25]

Key Terms

[edit | edit source]
array
A data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time by the program.[26]
associative array
An abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.[27]
hash table
A data structure used to implement an associative array, a structure that can map keys to values.[28]
index
A value, typically a numeric integer, used to identify and reference an array element.[29]
key
A data element which allows one to find an associated data value or values by using a database index, hash table or memory location.[30]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. An array is a _____ that is meant to _____.
An array is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time by the program.
2. Arrays are distinguished from lists in that _____.
Arrays are distinguished from lists in that arrays allow random access, while lists only allow sequential access. This feature allows a single iterative statement to process arbitrarily many elements of an array variable.
3. An index is _____.
An index is a value, typically a numeric integer, used to identify and reference an array element.
4. Array indexes start at _____, and correspondingly end at _____. PowerShell arrays are _____-based.
Array indexes start at either zero or one, depending on the programming language, and correspondingly end at either the number of elements minus one [0..n-1] or at the number of elements [1..n]. PowerShell arrays are zero-based.
5. The number of indices needed to specify an element is called the _____.
The number of indices needed to specify an element is called the dimension, dimensionality, or rank of the array type.
6. Dynamic arrays are _____.
Dynamic arrays are resizable and may be expanded at any time after creation, without changing the values of the current elements.
7. Index checking means that _____.
Index checking means that, in all expressions indexing an array, the index value is checked against the bounds of the array (which were established when the array was defined), and if the index is out-of-bounds, further execution is suspended via some sort of error.
8. A hash table is _____.
A hash table is a data structure used to implement an associative array, a structure that can map keys to values.
9. A hash table uses _____ to compute an index into an array of buckets or slots, from which the correct value can be found.
A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.
10. An associative array is _____.
An associative array is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.
11. PowerShell arrays are initialized using _____ syntax.
PowerShell arrays are initialized using @(value, value) syntax.
12. PowerShell array elements are accessed using _____ syntax.
PowerShell array elements are accessed using $array[element] syntax.
13. An empty PowerShell array is created using _____.
An empty PowerShell array is created using @().
14. PowerShell array elements are added using _____ syntax.
PowerShell array elements are added using $array += element syntax.
15. PowerShell array elements are removed using _____ syntax.
PowerShell array elements are removed using $array = $array[sub..set] + $array[sub..set] syntax.
16. PowerShell multi-dimensional array elements are accessed using _____ syntax.
PowerShell multi-dimensional array elements are accessed using $array[element][element] syntax.
17. PowerShell hash tables are initialized using _____ syntax.
PowerShell hash tables are initialized using @{key = value; key = value} syntax.
18. Hash table values are accessed using _____ syntax.
Hash table values are accessed using $table.key syntax.
19. An empty PowerShell hash table is created using _____.
An empty PowerShell hash table is created using @{}.
20. PowerShell hash table values are added using _____ syntax.
PowerShell hash table values are added using $table.Add(key, value) syntax or $table.key = value syntax.
21. PowerShell hash table values are removed using _____ syntax.
PowerShell hash table values are removed using $table.Remove(key) syntax.
22. The Format-Table cmdlet _____.
The Format-Table cmdlet formats hash table output as a table.
23. The Format-List cmdlet _____.
The Format-List cmdlet formats hash table output as a list of separate key-value pairs.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 9 - Functions

[edit | edit source]

This lesson introduces PowerShell functions.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic function concepts.
  • Understand recursion and when to use recursive functions.
  • Create PowerShell scripts that contain and use functions.

Readings

[edit | edit source]
  1. Wikipedia: Function (computer science)
  2. Wikipedia: Parameter (computer programming)
  3. Wikipedia: Recursion (computer science)
  4. BonusBits: Mastering PowerShell Chapter 9 - Functions

Multimedia

[edit | edit source]
  1. YouTube: Create a Simple FUNCTION in Powershell!
  2. YouTube: PowerShell - How To - Functions

Examples

[edit | edit source]

Get-Time

[edit | edit source]

Get-Time is a simple function that returns a value.

# The Get-Time function returns the current time.

function Get-Time()
{
    return Get-Date -DisplayHint Time
}

Get-Time

Get-cube

[edit | edit source]

Get-cube is a simple function that accepts a parameter and returns a value based on that parameter.

# The Get-cube function returns the cube (x^3) of the value provided.

function Get-cube([int]$x)
{
  $result = $x * $x * $x
  return $result
}

$x = Read-Host 'Enter a value'
$result = Get-cube $x
Write-Output "$x * $x * $x = $result"

Get-ByValue

[edit | edit source]

By default, PowerShell arguments are passed by value.[1]

function Get-ByValue($value)
{
    "value = $value"
    $value = 1
    "value = $value"
}

$x = 0
Get-ByValue $x
"x = $x"  

# Output:
# value = 0
# value = 1
# x = 0

Get-ByReference

[edit | edit source]

PowerShell arguments may be passed by reference using the Ref keyword.[2]

function Get-ByReference([ref]$ref)
{
    "ref = " + $ref.value
    $ref.value = 1
    "ref = " + $ref.value
}

$x = 0
Get-ByReference ([ref]$x)
"x = $x"

# Output:
# ref = 0
# ref = 1
# x = 1

Get-Args

[edit | edit source]

The $args array variable may be used to access a variable length parameter list.[3]

function Get-Args()
{
    foreach($arg in $args)
    {
        $arg
    }
}

Get-Args 1 2 3 4

Get-Parameters

[edit | edit source]

By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.[4]

function Show-Parameters($name, $number)
{
    "Name = $name, Number = $number"
}

Show-Parameters '1' 'Wiki'
Show-Parameters -number '1' -name 'Wiki'

# Output:
# Name = 1, Number = Wiki
# Name = Wiki, Number = 1

Show-FunctionScope

[edit | edit source]

By default, variables are available only in the scope in which they are created.[5]

function Show-FunctionScope()
{
    $x = 1
    "function x = $x"
}

$x = 0
Show-FunctionScope
"script x = $x"

# Output:
# function x = 1
# script x = 0

Show-ScriptScope

[edit | edit source]

You can use a scope modifier to change the scope of a variable.[6]

function Show-ScriptScope()
{
    $x = 1
    "function x = $x"
    $script:x = 2
}

$x = 0
Show-ScriptScope
"script x = $x"

# Output:
# function x = 1
# script x = 2

Get-Factorial

[edit | edit source]

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.[7]

# The Get-Factorial function returns the factorial of the value provided using recursion.

function Get-Factorial([int]$value)
{
    if($value -lt 0)
    {
        $result = 0
    }
    elseif($value -le 1)
    {
        $result = 1
    }
    else
    {
        $result = $value * (Get-Factorial($value - 1))
    }
    return $result
}

$value = Read-Host 'Enter a value'
$result = Get-Factorial $value
Write-Output "$value! = $result"

Activities

[edit | edit source]
  1. Create a script that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a condition statement to determine their selection, and use functions to convert years to months, years to days, years to hours, and years to seconds. Avoid global variables by passing parameters to the functions and returning values from the functions. Display their approximate age in the selected timeframe.
  2. Review MathsIsFun: Conversion of Temperature. Create a script that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a condition statement to determine their selection and then gather the appropriate input. Use functions to convert Fahrenheit to Celsius and Celsius to Fahrenheit. Avoid global variables by passing parameters to the functions and returning values from the functions. Calculate and display the converted temperature.
  3. Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user what shape they would like to calculate the area for. Use a condition statement to determine their selection and then gather the appropriate input. Use separate functions to calculate the area of each shape and then calculate and display the area of the selected shape. Avoid global variables by passing parameters to the functions and returning values from the functions.
  4. Review MathsIsFun: Greatest Common Factor. Create a script that asks the user to enter two integer values. Based on the recursive algorithm provided in Wikipedia: Recursion (computer science), use a recursive function to calculate the greatest common factor (greatest common divisor) of the two values and then display the result.

Lesson Summary

[edit | edit source]
  • A subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.[8]
  • A subroutine is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other subroutines, and then branch back (return) to the next instruction after the call once the subroutine's task is done.[9]
  • The content of a subroutine is its body, the piece of program code that is executed when the subroutine is called or invoked.[10]
  • A subroutine may be written so that it expects to obtain one or more data values from the calling program (its parameters or formal parameters). The calling program provides actual values for these parameters, called arguments.[11]
  • Subroutine arguments may be passed using call-by-reference or call-by-value.[12]
  • A subroutine may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.[13]
  • A subroutine can be coded so that it may call itself recursively, at one or more places, to perform its task.[14]
  • The advantages of breaking a program into subroutines include:[15]
    • decomposing a complex programming task into simpler steps
    • reducing duplicate code within a program
    • enabling reuse of code across multiple programs
    • hiding implementation details from users of the subroutine
  • Invoking a subroutine (versus using in-line code) imposes some computational overhead in the call mechanism.[16]
  • With call by value, a parameter acts within the subroutine as a variable initialized to the value of the argument (a local (isolated) copy of the argument).[17]
  • With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.[18]
  • Some languages allow subroutines to be defined to accept a variable number of arguments. For such languages, the subroutines must iterate through the list of arguments.[19]
  • Some programming languages allow subroutines to have named parameters.[20]
  • The PowerShell syntax for a declaring a function is:[21]
function name [(parameter list)] {statement list}
  • By default, PowerShell arguments are passed by value.[22]
  • PowerShell arguments may be passed by reference using the Ref keyword.[23]
  • By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.[24]
  • The $args array variable may be used to access a variable length parameter list.[25]
  • A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).[26]
  • The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached.[27]
  • Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.[28]

Key Terms

[edit | edit source]
call stack
A data structure that stores information about the active subroutines of a computer program.[29]
iteration
The repetition of a block of statements within a computer program.[30]
library
A collection of non-volatile resources used by programs on a computer, often to develop software.[31]
method
A subroutine associated with an object of a class that forms its interface through which other objects can access its encapsulated data.[32]
recursion
A method where the solution to a problem depends on solutions to smaller instances of the same problem.[33]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. A subroutine is _____.
A subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.
2. A subroutine is often coded so that it can _____, and then _____.
A subroutine is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other subroutines, and then branch back (return) to the next instruction after the call once the subroutine's task is done.
3. The content of a subroutine is its _____.
The content of a subroutine is its body, the piece of program code that is executed when the subroutine is called or invoked.
4. A subroutine may be written so that it expects to obtain one or more data values from the calling program _____. The calling program provides actual values for these _____, called _____.
A subroutine may be written so that it expects to obtain one or more data values from the calling program (its parameters or formal parameters). The calling program provides actual values for these parameters, called arguments.
5. Subroutine arguments may be passed using call-by-_____ or call-by-_____.
Subroutine arguments may be passed using call-by-reference or call-by-value.
6. A subroutine may also return a computed value to its caller _____, or provide various result values or _____.
A subroutine may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.
7. A subroutine can be coded so that it may call itself _____, at one or more places, to perform its task.
A subroutine can be coded so that it may call itself recursively, at one or more places, to perform its task.
8. The advantages of breaking a program into subroutines include:
The advantages of breaking a program into subroutines include:
  • decomposing a complex programming task into simpler steps
  • reducing duplicate code within a program
  • enabling reuse of code across multiple programs
  • hiding implementation details from users of the subroutine
13. Invoking a subroutine (versus using in-line code) imposes _____.
Invoking a subroutine (versus using in-line code) imposes some computational overhead in the call mechanism.
14. With call by value, _____.
With call by value, a parameter acts within the subroutine as a variable initialized to the value of the argument (a local (isolated) copy of the argument).
15. With call by reference, _____.
With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.
16. Some languages allow subroutines to be defined to accept a variable number of arguments. For such languages, the subroutines must _____.
Some languages allow subroutines to be defined to accept a variable number of arguments. For such languages, the subroutines must iterate through the list of arguments.
17. Some programming languages allow subroutines to have named _____.
Some programming languages allow subroutines to have named parameters.
18. By default, PowerShell arguments are passed using call by _____.
By default, PowerShell arguments are passed using call by value.
19. PowerShell arguments may be passed by reference using the _____ keyword.
PowerShell arguments may be passed by reference using the Ref keyword.
20. By default, PowerShell arguments are passed by position. _____ may be used to identify parameters, bypassing position.
By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.
21. The $args array variable may be used to _____.
The $args array variable may be used to access a variable length parameter list.
22. A recursive function definition has _____, and _____.
A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).
23. The job of the recursive cases can be seen as _____. In a properly designed recursive function, with each recursive call, the input problem must be _____.
The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached.
24. Recursive programming solutions include _____.
Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 10 - Errors

[edit | edit source]

This lesson introduces PowerShell debugging, error handling, and parameter validation.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic PowerShell debugging concepts.
  • Explain PowerShell error handling.
  • Understand PowerShell parameter validation.
  • Create PowerShell scripts that use Try Catch Finally.
  • Create PowerShell functions that perform parameter validation.

Readings

[edit | edit source]
  1. Wikipedia: Debugging
  2. Wikipedia: Error handling
  3. Wikipedia: Parameter validation
  4. Wikipedia: Data validation
  5. MSDN: An Introduction to Error Handling in PowerShell
  6. WindowsITPro: Error Trapping and Handling in PowerShell
  7. Microsoft TechNet: Simplify your PowerShell Script with Parameter Validation

Multimedia

[edit | edit source]
  1. YouTube: Handle Powershell Errors With Try Catch
  2. YouTube: Windows PowerShell Error handling with Try...Catch
  3. YouTube: Introduction to Advanced Function Parameters in PowerShell
  4. YouTube: PowerShell - How To - Defining Parameters

Examples

[edit | edit source]

Try Catch

[edit | edit source]

Use Try, Catch, and Finally blocks to respond to or handle terminating errors in scripts.[1]

try
{
    $value = Read-Host 'Enter a value'
    $result = 1 / $value
    Write-Output "1 / $value = $result"

}
catch
{
    Write-Output "An error occurred dividing 1 by $value!"
}

Data Type Validation

[edit | edit source]
function Get-Square()
{
    Param
    (
        [double]$value
    )
    return $value * $value   
}

Mandatory Validation

[edit | edit source]

The Mandatory argument indicates that the parameter is required.[2]

function Get-Square()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [double]$value
    )
    return $value * $value   
}

Range Validation

[edit | edit source]

The ValidateRange attribute specifies a numeric range for each parameter or variable value.[3]

function Get-Square()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateRange(1,10)]
        [double]$value
    )
    return $value * $value   
}

Not Null or Empty Validation

[edit | edit source]

The ValidateNotNullOrEmpty attribute specifies that the parameter value cannot be null ($null) and cannot be an empty string ("").[4]

function Get-Posessive()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$value
    )
    if($value.Substring($value.Length - 1, 1) -eq 's')
    {
        $result = $value + ''''
    }
    else
    {
        $result = $value + '''s'
    }
    return $result
}

Length Validation

[edit | edit source]

The ValidateLength attribute specifies the minimum and maximum number of characters in a parameter or variable value.[5]

function Check-ZipCode()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateLength(5,5)]
        [string]$value
    )
    return $value
}

Pattern Validation

[edit | edit source]

The ValidatePattern attribute specifies a regular expression that is compared to the parameter or variable value.[6]

function Check-ZipCode()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidatePattern('^\d{5}$|^\d{5}-\d{4}$')]
        [string]$value
    )
    return $value
}

Script Validation

[edit | edit source]

The ValidateScript attribute specifies a script that is used to validate a parameter or variable value.[7]

function Get-Reciprocal()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateScript({$_ -ne 0})]
        [double]$value
    )
    return 1 / $value   
}

Error Handling and Parameter Validation

[edit | edit source]

Error handling and parameter validation may be combined, but the error handling of parameter validation must occur in the calling code rather than within the function.

function Get-Reciprocal()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateScript({$_ -ne 0})]
        [double]$value
    )
    return 1 / $value   
}

try
{
    $value = Read-Host 'Enter a value'
    $result = Get-Reciprocal $value
    Write-Output "1 / $value = $result"
}
catch
{
    Write-Output "An error occurred dividing 1 by $value!"
}

Activities

[edit | edit source]
  1. Review MCP Mag:Validation Voodoo with PowerShell Scripts. Create a script that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a condition statement to determine their selection, and use functions to convert years to months, years to days, years to hours, and years to seconds. Display their approximate age in the selected timeframe. Add parameter validation to the functions and exception handling to the script to handle any errors that could occur during the calculations.
  2. Review MathsIsFun: Conversion of Temperature. Create a script that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a condition statement to determine their selection and then gather the appropriate input. Use functions to convert Fahrenheit to Celsius and Celsius to Fahrenheit. Calculate and display the converted temperature. Add parameter validation to the functions and exception handling to the script to handle any errors that could occur during the calculations.
  3. Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user what shape they would like to calculate the area for. Use a condition statement to determine their selection and then gather the appropriate input. Use separate functions to calculate the area of each shape and then calculate and display the area of the selected shape. Add parameter validation to the functions and exception handling to the script to handle any errors that could occur during the calculations.
  4. Review MathsIsFun: Greatest Common Factor. Create a script that asks the user to enter two integer values. Based on the recursive algorithm provided in Wikipedia: Recursion (computer science), use a recursive function to calculate the greatest common factor (greatest common divisor) of the two values and then display the result. Add parameter validation to the functions and exception handling to the script to handle any errors that could occur during the calculations.

Lesson Summary

[edit | edit source]
  • Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware.[8]
  • Debugging includes interactive debugging, control flow, integration testing, log files, monitoring, memory dumps, profiling, Statistical Process Control, and special design tactics to improve detection while simplifying changes.[9]
  • The typical debugging process:[10]
    • Normally the first step in debugging is to attempt to reproduce the problem.
    • After the bug is reproduced, the input of the program may need to be simplified to make it easier to debug.
    • After the test case is sufficiently simplified, a programmer can use a debugger tool to examine program states (values of variables, plus the call stack) and track down the origin of the problem(s).
    • Alternatively, tracing can be used. In simple cases, tracing is just a few print statements, which output the values of variables at certain points of program execution.
  • Exception handling is the process of responding to the occurrence, during computation, of anomalous or exceptional events requiring special processing, often changing the normal flow of program execution.[11]
  • In general, exceptions are handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are continuable, the handler may later resume the execution at the original location using the saved information.[12]
  • Alternative approaches to exception handling in software are error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values or some auxiliary global variable.[13]
  • In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote a data structure storing information about an exceptional condition.[14]
  • One mechanism to transfer control, or raise an exception, is known as a throw.[15]
  • The scope for exception handlers starts with a "try" clause.[16]
  • An exception is said to be thrown and execution is transferred to a "catch".[17]
  • A related "finally" clause is executed whether an exception occurred or not, typically to release resources acquired within the body of the exception-handling block.[18]
  • Parameter validation is the automated processing, in a module, to validate the accuracy of parameters passed to that module.[19]
  • Data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines that check for correctness, meaningfulness, and security of data that are input to the system.
  • Data validation examples include:[20]
    • Data type validation
    • Range and constraint validation
    • Code and cross-reference validation
    • Structured (advanced) validation
  • Data validation responses include errors that terminate processing and warnings that inform the user but allow processing to continue.[21]
  • Data validation failures or omissions can lead to data corruption or security vulnerabilities.[22]
  • PowerShell parameter validation options include:[23]
    • parameter(Mandatory=$true)
    • ValidateRange
    • ValidateNotNullOrEmpty
    • ValidateLength
    • ValidatePattern
    • ValidateScript

Key Terms

[edit | edit source]
assertion
A true–false statement placed in a program to indicate that the developer thinks that the statement is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort.[24]
debugger
A computer program that is used to test and debug other programs.[25]
divide and conquer algorithm
An approach of recursively breaking down a problem into two or more sub-problems of the same (or related) type, until these become simple enough to be solved directly.[26]
integration testing
The phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing.[27]
log file
A file that records events which happen while a system or application runs.[28]
mission-critical
Any factor of a system whose failure will result in the failure of business operations.[29]
memory dump
The recorded state of the working memory of a computer program at a specific time, generally when the program has terminated abnormally (crashed).[30]
patch
A piece of software designed to update a computer program or its supporting data, to fix or improve it.[31]
print debugging
The act of watching trace statements, or print statements, that indicate the flow of execution of a process.[32]
profiling
A form of dynamic program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or the frequency and duration of function calls.[33]
tracing
A specialized use of logging to record information about a program's execution.[34]
unit testing
A software testing method by which individual blocks of source code are tested to determine if they are fit for use.[35]
validation testing
The process of checking that a software system meets specifications and that it fulfills its intended purpose.[36]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Debugging is _____.
Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware.
2. Debugging includes _____, _____, _____, _____, _____, _____, _____, _____, and _____.
Debugging includes interactive debugging, control flow, integration testing, log files, monitoring, memory dumps, profiling, Statistical Process Control, and special design tactics to improve detection while simplifying changes.
3. The typical debugging process includes:
The typical debugging process includes:

Normally the first step in debugging is to attempt to reproduce the problem.
After the bug is reproduced, the input of the program may need to be simplified to make it easier to debug.
After the test case is sufficiently simplified, a programmer can use a debugger tool to examine program states (values of variables, plus the call stack) and track down the origin of the problem(s).
Alternatively, tracing can be used. In simple cases, tracing is just a few print statements, which output the values of variables at certain points of program execution.

4. Exception handling is _____.
Exception handling is the process of responding to the occurrence, during computation, of anomalous or exceptional events requiring special processing, often changing the normal flow of program execution.
5. In general, exceptions are handled (resolved) by _____.
In general, exceptions are handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are continuable, the handler may later resume the execution at the original location using the saved information.
6. Alternative approaches to exception handling in software are _____.
Alternative approaches to exception handling in software are error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values or some auxiliary global variable.
7. In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote _____.
In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote a data structure storing information about an exceptional condition.
8. One mechanism to transfer control, or raise an exception, is known as _____.
One mechanism to transfer control, or raise an exception, is known as a throw.
9. The scope for exception handlers starts with _____.
The scope for exception handlers starts with a "try" clause.
10. An exception is said to be thrown and execution is transferred to _____.
An exception is said to be thrown and execution is transferred to a "catch".
11. A related _____ is executed whether an exception occurred or not, typically to release resources acquired within the body of the exception-handling block.
A related "finally" clause is executed whether an exception occurred or not, typically to release resources acquired within the body of the exception-handling block.
12. Parameter validation is _____.
Parameter validation is the automated processing, in a module, to validate the accuracy of parameters passed to that module.
13. Data validation is _____.
Data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines that check for correctness, meaningfulness, and security of data that are input to the system.
14. Data validation examples include:
Data validation examples include:

Data type validation
Range and constraint validation
Code and cross-reference validation
Structured (advanced) validation

15. Data validation responses include _____ and _____.
Data validation responses include errors that terminate processing and warnings that inform the user but allow processing to continue.
16. Data validation failures or omissions can lead to _____.
Data validation failures or omissions can lead to data corruption or security vulnerabilities.
17. PowerShell parameter validation options include:
PowerShell parameter validation options include:

parameter(Mandatory=$true)
ValidateRange
ValidateNotNullOrEmpty
ValidateLength
ValidatePattern
ValidateScript

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 11 - File System

[edit | edit source]

This lesson introduces PowerShell file system processing.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic PowerShell file system concepts.
  • Create PowerShell scripts to manage files and folders.
  • Create PowerShell scripts to read and write text file content.

Readings

[edit | edit source]
  1. Wikipedia: File system
  2. Wikipedia: Directory (computing)
  3. Wikipedia: Directory structure
  4. Wikipedia: Text file
  5. BonusBits: Mastering PowerShell Chapter 15 - The File System

Multimedia

[edit | edit source]
  1. YouTube: Creating Files and Folders in PowerShell
  2. YouTube: Grab content from a file in Powershell
  3. YouTube: PowerShell - How To - Working with TXT and CSV Files

Examples

[edit | edit source]

Get-ChildItem

[edit | edit source]

The Get-ChildItem cmdlet gets items and child items from a given location.[1] It is similar in concept to a DIR command to list files in a directory.

Get-ChildItem -Path 'C:\'             # List all files in the root directory.
Get-ChildItem -Path 'C:\' -Recurse    # List all files on the C drive.

New-Item

[edit | edit source]

The New-Item cmdlet creates a new item of the given type at the given path location.[2]

New-Item -Path 'C:\' -Name 'PSTest' -ItemType Directory
New-Item -Path 'C:\PSTest' -Name 'Test.txt' -ItemType File -Value 'This is a test.'

Move-Item

[edit | edit source]

The Move-Item cmdlet moves an item from the given path location to the given destination.[3]

Move-Item -Path 'C:\PSTest\Test.txt' -Destination 'C:\PSTest\Test2.txt'

Copy-Item

[edit | edit source]

The Copy-Item cmdlet copies an item from the given path location to the given destination.[4]

Copy-Item -Path 'C:\PSTest\Test2.txt' -Destination 'C:\PSTest\Test.txt'

Remove-Item

[edit | edit source]

The Remove-Item cmdlet removes an item from the given path location.[5]

Remove-Item -Path 'C:\PSTest\Test.txt'
Remove-Item -Path 'C:\PSTest' -Recurse

Test-Path

[edit | edit source]

The Test-Path cmdlet determines whether a path exists.[6]

$filename = 'example.txt'
if((Test-Path $filename) -ne $true)
{
    Write-Output "$filename not found!"
}

Set-Content

[edit | edit source]

The Set-Content cmdlet is a string-processing cmdlet that writes or replaces the content in the specified item, such as a file.[7]

$path = $HOME + '\My PowerShell Content.txt'
$value =  @('Colors', 'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet')
Set-Content -Path $path -Value $value

Add-Content

[edit | edit source]

The Add-Content cmdlet appends content to a specified item or file.[8]

$path = $HOME + '\My PowerShell Content.txt'
Add-Content -Path $path -Value 'Brown'
Add-Content -Path $path -Value 'Black'

Get-Content

[edit | edit source]

The Get-Content cmdlet gets the content of a given item.[9]

$path = $HOME + '\My PowerShell Content.txt'
$content = Get-Content -Path $path
foreach ($line in $content)
{
    Write-Output $line
}

Clear-Content

[edit | edit source]

The Clear-Content cmdlet deletes the contents of an item, such as deleting the text from a file, but it does not delete the item.[10]

$path = $HOME + '\My PowerShell Content.txt'
Clear-Content -Path $path

Activities

[edit | edit source]
  1. Review Microsoft TechNet: Using the Get-ChildItem Cmdlet. Experiment with using Get-ChildItem to retrieve directory listings.
  2. Review Microsoft TechNet: Using the New-Item Cmdlet. Experiment with creating folders and files.
  3. Review Microsoft TechNet: Using the Move-Item Cmdlet. Experiment with moving folders and files.
  4. Review Microsoft TechNet: Using the Copy-Item Cmdlet. Experiment with copying folders and files.
  5. Review Microsoft TechNet: Using the Remove-Item Cmdlet. Experiment with removing folders and files.
  6. Review Microsoft TechNet: Using the Get-Content Cmdlet. Use the Get-Content cmdlet to read a file and process the file content line by line. For example, create a file with student names and test scores. Process the file line by line and display the average score for the class. Use Test-Path to verify that the file path exists before getting the file content, and a Try-Catch-Finally block to handle any errors that occur during file processing.
  7. Review WindowsITPro: Get Hex Dumps of Files in PowerShell. Use the Get-Content cmdlet and with -Encoding Byte and -ReadCount 1 to read one character at a time and then display each character's ASCII value. Display a multi-line text file and verify that each line does, indeed, end with CR and LF characters (13 and 10).

Lesson Summary

[edit | edit source]
  • A file system is used to control how data is stored and retrieved. There are many different kinds of file systems. Each one has different structure and logic, properties of speed, flexibility, security, size and more.[11]
  • File systems are responsible for arranging storage space; reliability, efficiency, and tuning with regard to the physical storage medium are important design considerations.[12]
  • File systems allocate space in a granular manner, usually multiple physical units on the device.[13]
  • A filename (or file name) is used to identify a storage location in the file system.[14]
  • File systems typically have directories (also called folders) which allow the user to group files into separate collections.[15]
  • A file system stores all the metadata associated with the file—including the file name, the length of the contents of a file, and the location of the file in the folder hierarchy—separate from the contents of the file.[16]
  • Directory utilities may be used to create, rename and delete directory entries.[17]
  • File utilities create, list, copy, move and delete files, and alter metadata.[18]
  • All file systems have some functional limit that defines the maximum storable data capacity within that system.[19]
  • A directory is a file system cataloging structure which contains references to other computer files, and possibly other directories.[20]
  • A text file is a kind of computer file that is structured as a sequence of lines of electronic text.[21]
  • MS-DOS and Windows use a common text file format, with each line of text separated by a two-character combination: CR and LF, which have ASCII codes 13 and 10.[22]
  • The Get-ChildItem cmdlet gets items and child items from a given location.[23]
  • The New-Item cmdlet creates a new item of the given type at the given path location.[24]
  • The Move-Item cmdlet moves an item from the given path location to the given destination.[25]
  • The Copy-Item cmdlet copies an item from the given path location to the given destination.[26]
  • The Remove-Item cmdlet removes an item from the given path location.[27]
  • The Test-Path cmdlet determines whether a path exists.[28]
  • The Set-Content cmdlet is a string-processing cmdlet that writes or replaces the content in the specified item, such as a file.[29]
  • The Add-Content cmdlet appends content to a specified item or file.[30]
  • The Get-Content cmdlet gets the content of a given item.[31]
  • The Clear-Content cmdlet deletes the contents of an item, such as deleting the text from a file, but it does not delete the item.[32]

Key Terms

[edit | edit source]
ASCII (American Standard Code for Information Interchange)
A character-encoding scheme originally based on the English alphabet which encodes 128 specified characters into 7-bit binary integers.[33]
descriptive metadata
Data about individual instances of application data, or data content.[34]
file system fragmentation
The inability of a file system to lay out related data sequentially (contiguously)[35]
flat file system
A file system in which there are no subdirectories.[36]
hierarchical filesystem
A filesystem in which files and directories are organized in a manner that resembles a tree.[37]
metadata
Data about data, including structural metadata and descriptive metadata.[38]
root
The top-most directory in a hierarchical filesystem.[39]
structural metadata
Data about the design and specification of data structures, or the containers of data.[40]
subdirectory
A directory contained inside another directory.[41]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. A file system is used to control _____. There are many different kinds of file systems. Each one has different _____, properties of _____, _____, _____, _____ and more.
A file system is used to control how data is stored and retrieved. There are many different kinds of file systems. Each one has different structure and logic, properties of speed, flexibility, security, size and more.
2. File systems are responsible for _____; _____, _____, and _____ are important design considerations.
File systems are responsible for arranging storage space; reliability, efficiency, and tuning with regard to the physical storage medium are important design considerations.
3. File systems allocate space in a _____ manner, usually with _____.
File systems allocate space in a granular manner, usually with multiple physical units on the device.
4. A filename (or file name) is used to _____.
A filename (or file name) is used to identify a storage location in the file system.
5. File systems typically have directories (also called folders) which _____.
File systems typically have directories (also called folders) which allow the user to group files into separate collections.
6. A file system stores all the metadata associated with the file—including _____, _____, and _____—separate from the contents of the file.
A file system stores all the metadata associated with the file—including the file name, the length of the contents of a file, and the location of the file in the folder hierarchy—separate from the contents of the file.
7. Directory utilities may be used to _____, _____ and _____ directory entries.
Directory utilities may be used to create, rename and delete directory entries.
8. File utilities _____, _____, _____, _____ and _____ files, and alter metadata.
File utilities create, list, copy, move and delete files, and alter metadata.
9. All file systems have some functional limit that defines _____.
All file systems have some functional limit that defines the maximum storable data capacity within that system.
10. A directory is a file system cataloging structure which _____.
A directory is a file system cataloging structure which contains references to other computer files, and possibly other directories.
11. A text file is a kind of computer file that is _____.
A text file is a kind of computer file that is structured as a sequence of lines of electronic text.
12. MS-DOS and Windows use a common text file format, with each line of text separated by _____.
MS-DOS and Windows use a common text file format, with each line of text separated by a two-character combination: CR and LF, which have ASCII codes 13 and 10.
13. The Get-ChildItem cmdlet _____.
The Get-ChildItem cmdlet gets items and child items from a given location.
14. The New-Item cmdlet _____.
The New-Item cmdlet creates a new item of the given type at the given path location.
15. The Move-Item cmdlet _____.
The Move-Item cmdlet moves an item from the given path location to the given destination.
16. The Copy-Item cmdlet _____.
The Copy-Item cmdlet copies an item from the given path location to the given destination.
17. The Remove-Item cmdlet _____.
The Remove-Item cmdlet removes an item from the given path location.
18. The Test-Path cmdlet _____.
The Test-Path cmdlet determines whether a path exists.
19. The Set-Content cmdlet _____.
The Set-Content cmdlet is a string-processing cmdlet that writes or replaces the content in the specified item, such as a file.
20. The Add-Content cmdlet _____.
The Add-Content cmdlet appends content to a specified item or file.
21. The Get-Content cmdlet _____.
The Get-Content cmdlet gets the content of a given item.
22. The Clear-Content cmdlet _____.
The Clear-Content cmdlet deletes the contents of an item, such as deleting the text from a file, but it does not delete the item.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 12 - Registry

[edit | edit source]

This lesson introduces PowerShell Registry processing.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic PowerShell Windows Registry concepts.
  • Create PowerShell scripts to manage Registry keys.

Readings

[edit | edit source]
  1. Wikipedia: Windows Registry
  2. Wikipedia: INI file
  3. BonusBits: Mastering PowerShell Chapter 16 - The Registry

Multimedia

[edit | edit source]
  1. YouTube: Working With Registry Items In Powershell
  2. YouTube: Windows PowerShell - How To - Windows Registry

Examples

[edit | edit source]

Get-PSDrive

[edit | edit source]

The Get-PSDrive cmdlet gets the drives available in the current session, including logical mapped network drives and drives exposed by Windows PowerShell providers.[1]

Get-PSDrive -PSProvider Registry

Example output:

PS C:\Windows\system32> Get-PSDrive

Name           Used (GB)     Free (GB) Provider      Root                                               CurrentLocation
----           ---------     --------- --------      ----                                               ---------------
Alias                                  Alias
C                  56.04        408.13 FileSystem    C:\                                               Windows\system32
Cert                                   Certificate   \
D                                      FileSystem    D:\
Env                                    Environment
Function                               Function
HKCU                                   Registry      HKEY_CURRENT_USER
HKLM                                   Registry      HKEY_LOCAL_MACHINE
Variable                               Variable
WSMan                                  WSMan

New-Item

[edit | edit source]

The New-Item cmdlet creates a new item and sets its value.[2]

$path = 'HKCU:\Software\Scripts'
if(!(Test-Path -Path $path))
{
    New-Item -Path $path
}

$path = 'HKCU:\Software\Scripts\My Script'
if(!(Test-Path -Path $path))
{
    New-Item -Path $path
}

New-ItemProperty

[edit | edit source]

The New-ItemProperty cmdlet creates a new property for an item and sets its value.[3]

$path = 'HKCU:\Software\Scripts\My Script'
$name = 'RunCount'
New-ItemProperty -Path $path -Name $name -PropertyType DWord -Value 0

Get-Item

[edit | edit source]

The Get-Item cmdlet gets the item at the specified location.[4]

$path = 'HKCU:\Software\Scripts\My Script'
$key = Get-Item -Path $path
foreach($name in $key.Property)
{
    $property = Get-ItemProperty -Path $path -Name $name
    Write-Output ($name + ' = ' + $property.$name)
}

Get-ItemProperty

[edit | edit source]

The Get-ItemProperty cmdlet gets the properties of a specified item.[5]

$path = 'HKCU:\Software\Scripts\My Script'
try
{
    $name = 'RunCount'
    $key = Get-ItemProperty -Path $path -Name $name -ErrorAction Stop
    $runs = $key.RunCount
}
catch
{
    $runs = 0
}

Set-ItemProperty

[edit | edit source]

The Set-ItemProperty cmdlet changes the value of the property of the specified item.[6]

$path = 'HKCU:\Software\Scripts\My Script'
$name = 'RunCount'
$runs++
Set-ItemProperty -Path $path -Name $name -Value $runs

Remove-Item

[edit | edit source]

The Remove-Item cmdlet deletes one or more items.[7]

$path = 'HKCU:\Software\Scripts\My Script'
Remove-Item -Path $path -Confirm

Remove-ItemProperty

[edit | edit source]

The Remove-ItemProperty cmdlet deletes a property and its value from an item.[8]

$path = 'HKCU:\Software\Scripts\My Script'
$name = 'RunCount'
Remove-ItemProperty -Path $path -Name $name -Confirm

Activities

[edit | edit source]
  1. Review Microsoft TechNet: Use PowerShell to Back Up System State Prior to Making Changes. Use the Checkpoint-Computer cmdlet to create a system restore point.
  2. Review Microsoft TechNet: Using the Get-PSDrive Cmdlet. Use the Get-PSDrive cmdlet to display available drives. Identify the drive names supported by the Registry provider. Use a foreach loop and the Get-ChildItem (alias Dir) cmdlet to display the root keys available in the registry drives.
  3. Review PowerShell.com: The Registry. Create a script that uses a foreach loop to display all Registry entries that contain the word 'PowerShell' in the key or the value.
  4. Review CrucialSecurityBlog: Typed URLs. Create a script that uses a foreach loop to display Internet Explorer history (Internet Explorer Typed Urls).
  5. Review Microsoft MSDN: Run and RunOnce Registry Keys. Create a script to add a RunOnce item to automatically run either PowerShell or PowerShell ISE (your choice) at the next logon.
  6. Review AskVG.com: How to Enable “Open Command Window Here” Option in Context Menu in Windows Vista and 7. Create a script to delete the 'Extended' item property from the following keys. Be sure to use the -Confirm option and carefully confirm that only the Extended property will be removed. Use Windows Explorer to confirm that 'Open command window here' now appears on the context menu without holding down the Shift key.
    • HKLM:\SOFTWARE\Classes\Directory\shell\cmd
    • HKLM:\SOFTWARE\Classes\Drive\shell\cmd

Lesson Summary

[edit | edit source]
  • The Windows Registry is a hierarchical database that stores configuration settings and options on Microsoft Windows operating systems.[9]
  • The Registry supports strongly-typed data values, while INI files are text only.[10]
  • Regedit.exe is the built-in Windows Registry editor.[11]
  • The Registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys may contain values or further keys.[12]
  • Keys are referenced with a syntax similar to Windows' path names, using backslashes to indicate levels of hierarchy. Keys must have a case insensitive name without backslashes.[13]
  • The keys at the root level of the hierarchical database are generally named by their Windows API definitions, which all begin "HKEY".[14]
  • HKEY_LOCAL_MACHINE, abbreviated as HKLM, stores settings that are specific to the local computer.[15]
  • HKEY_CURRENT_USER abbreviated HKCU, stores settings that are specific to the currently logged-in user[16]
  • The INI file format is a simple text file with a basic structure composed of sections, properties, and values used primarily in MS-DOS and 16-bit versions of Windows.[17]
  • Windows NT and later versions of Windows use the Registry for configuration settings.[18]
  • Applications built on the .NET Framework and portable applications often use XML-format configuration files rather than the Registry.[19]
  • The PowerShell Registry provider exposes two registry paths: HKLM for HKEY_LOCAL_MACHINE and HKCU for HKEY_CURRENT_USER.[20]
  • The Get-PSDrive cmdlet gets the drives available in the current session, including logical mapped network drives and drives exposed by Windows PowerShell providers.[21]
  • The New-Item cmdlet creates a new item and sets its value.[22]
  • The New-ItemProperty cmdlet creates a new property for an item and sets its value.[23]
  • The Get-Item cmdlet gets the item at the specified location.[24]
  • The Get-ItemProperty cmdlet gets the properties of a specified item.[25]
  • The Set-ItemProperty cmdlet changes the value of the property of the specified item.[26]
  • The Remove-Item cmdlet deletes one or more items.[27]
  • The Remove-ItemProperty cmdlet deletes a property and its value from an item.[28]

Key Terms

[edit | edit source]
hive
A logical group of keys, subkeys, and values in the Registry that has a set of supporting files containing backups of its data.[29]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. The Windows Registry is _____.
The Windows Registry is a hierarchical database that stores configuration settings and options on Microsoft Windows operating systems.
1. The Registry supports _____ data values, while INI files are _____.
The Registry supports strongly-typed data values, while INI files are text only.
1. Regedit.exe is _____.
Regedit.exe is the built-in Windows Registry editor.
2. The Registry contains two basic elements: _____ and _____.
The Registry contains two basic elements: keys and values.
3. Registry keys are container objects similar to _____. Registry values are non-container objects similar to _____. Keys may contain _____.
The Registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys may contain values or further keys.
4. Keys are referenced with a syntax similar to Windows' path names, using _____. Keys must have _____.
Keys are referenced with a syntax similar to Windows' path names, using backslashes to indicate levels of hierarchy. Keys must have a case insensitive name without backslashes.
5. The keys at the root level of the hierarchical database are generally named by their Windows API definitions, which all begin _____.
The keys at the root level of the hierarchical database are generally named by their Windows API definitions, which all begin "HKEY".
6. HKEY_LOCAL_MACHINE, abbreviated as HKLM, stores _____.
HKEY_LOCAL_MACHINE, abbreviated as HKLM, stores settings that are specific to the local computer.
7. HKEY_CURRENT_USER abbreviated HKCU, stores _____.
HKEY_CURRENT_USER abbreviated HKCU, stores settings that are specific to the currently logged-in user.
8. The INI file format is _____ used primarily in _____.
The INI file format is a simple text file with a basic structure composed of sections, properties, and values used primarily in MS-DOS and 16-bit versions of Windows.
9. Windows NT and later versions of Windows use _____ for configuration settings.
Windows NT and later versions of Windows use the Registry for configuration settings.
10. Applications built on the .NET Framework and portable applications often use _____ rather than the Registry.
Applications built on the .NET Framework and portable applications often use XML-format configuration files rather than the Registry.
11. The PowerShell Registry provider _____.
The PowerShell Registry provider exposes two registry paths: HKLM for HKEY_LOCAL_MACHINE and HKCU for HKEY_CURRENT_USER.
12. The Get-PSDrive cmdlet _____.
The Get-PSDrive cmdlet gets the drives available in the current session, including logical mapped network drives and drives exposed by Windows PowerShell providers.
13. The New-Item cmdlet _____.
The New-Item cmdlet creates a new item and sets its value.
14. The New-ItemProperty cmdlet _____.
The New-ItemProperty cmdlet creates a new property for an item and sets its value.
15. The Get-Item cmdlet _____.
The Get-Item cmdlet gets the item at the specified location.
16. The Get-ItemProperty cmdlet _____.
The Get-ItemProperty cmdlet gets the properties of a specified item.
17. The Set-ItemProperty cmdlet _____.
The Set-ItemProperty cmdlet changes the value of the property of the specified item.
18. The Remove-Item cmdlet _____.
The Remove-Item cmdlet deletes one or more items.
19. The Remove-ItemProperty cmdlet _____.
The Remove-ItemProperty cmdlet deletes a property and its value from an item.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 13 - WMI

[edit | edit source]

This lesson introduces PowerShell systems management using Windows Management Instrumentation (WMI), Remote WMI, and PowerShell Remoting.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic PowerShell WMI concepts.
  • Create PowerShell scripts to process WMI content.
  • Use PowerShell Remoting to run commands on a remote computer.

Readings

[edit | edit source]
  1. Wikipedia: Systems management
  2. Wikipedia: Windows Management Instrumentation
  3. BonusBits: Mastering PowerShell Chapter 18 - WMI
  4. Windows IT Pro: PowerShell Basics: Remote Management

Multimedia

[edit | edit source]
  1. YouTube: WMI and PowerShell

Examples

[edit | edit source]

Get-WmiObject List

[edit | edit source]

The Get-WmiObject cmdlet gets instances of WMI classes or information about the available WMI classes.[1]

Get-WmiObject -List

Win32_BIOS

[edit | edit source]

The Win32_BIOS WMI class represents the attributes of the computer system's basic input/output services (BIOS) that are installed on a computer.[2]

Get-WmiObject -Class Win32_BIOS

Win32_ComputerSystem

[edit | edit source]

The Win32_ComputerSystem class represents a computer system operating in a Windows environment.[3]

Get-WmiObject -Class Win32_ComputerSystem

Example output:

Domain              : MY_DOMAIN_NAME
Manufacturer        : MY_COMPUTER_Manufacturer_Inc.
Model               : My_Model
Name                : My_Computer_name
PrimaryOwnerName    :
TotalPhysicalMemory : 17024573440

Win32_NetworkAdapterConfiguration

[edit | edit source]

The Win32_NetworkAdapterConfiguration class represents the attributes and behaviors of a network adapter.[4]

Get-WmiObject -Class Win32_NetworkAdapterConfiguration

win32_logicaldisk

[edit | edit source]

The win32_logicaldisk class presents information about logicaldisks, size and free space available.

get-WmiObject win32_logicaldisk

DeviceID     : C:
DriveType    : 3
ProviderName :
FreeSpace    : 438228828160
Size         : 498396557312
VolumeName   : OS

DeviceID     : D:
DriveType    : 5
ProviderName :
FreeSpace    :
Size         :
VolumeName   :

Get-PSDrive command can also be used to obtain disk information.

Get-Member

[edit | edit source]

The Get-Member cmdlet gets the members (properties and methods) of objects.[5]

Get-WmiObject -Class Win32_BIOS | Get-Member

Object properties may be accessed using . notation.

$bios = Get-WmiObject -Class Win32_BIOS
'Computer Name: ' + $bios.PSComputerName
'Manufacturer:  ' + $bios.Manufacturer
'BIOS Version:  ' + $bios.SMBIOSBIOSVersion

Object methods are called the same way.

$service = Get-WmiObject -Class Win32_Service -Filter "Name='Spooler'"
$service.StopService()
$service.StartService()

Enable Remote WMI

[edit | edit source]

The following command enables remote WMI traffic through the local Windows firewall.[6]

netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes

Disable Remote WMI

[edit | edit source]

The following command disables remote WMI traffic through the local Windows firewall.[7]

netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=no

Use Remote WMI

[edit | edit source]

The Get-WmiObject cmdlet may be used to connect to remote computers using the -ComputerName parameter, with a specified Credential if necessary.[8]

Get-WmiObject -Class Win32_BIOS -ComputerName 'RemoteHost'

Get-WmiObject -Class Win32_BIOS -ComputerName 'RemoteHost' -Credential 'RemoteHost\Username'

Enable-PSRemoting

[edit | edit source]

The Enable-PSRemoting cmdlet configures the computer to receive Windows PowerShell remote commands that are sent by using the WS-Management technology.[9]

Enable-PSRemoting -Force

Disable-PSRemoting

[edit | edit source]

The Disable-PSRemoting cmdlet prevents users on other computers from running commands on the local computer.[10]

Disable-PSRemoting -Force

Trusted Hosts

[edit | edit source]

TrustedHosts allows a local computer to send authentication credentials to a remote computer in a non-domain environment. The Set-Item cmdlet is used to add a remote host to the TrustedHosts list. Specify the computer name or IP address for the RemoteHost.[11][12]

Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value 'RemoteHost'

Enter-PSSession

[edit | edit source]

The Enter-PSSession cmdlet starts an interactive PowerShell session with a single remote computer. During the session, the commands that you type run on the remote computer, just as though you were typing directly on the remote computer. You can have only one interactive session at a time.[13]

Enter-PSSession -Computer RemoteHost

Exit-PSSession

[edit | edit source]

The Exit-PSSession cmdlet ends interactive sessions that you started by using Enter-PSSession.[14]

Exit-PSSession

Activities

[edit | edit source]
  1. Review Microsoft TechNet: Using the Get-WMiObject Cmdlet. Create a script to retrieve BIOS information from the local system. Compare the results with the most recent BIOS version available from your system's manufacturer. If a BIOS update is available, review the update information and determine whether or not you should upgrade your BIOS.
  2. Create a script that uses the WMI Win32_ComputerSystem and Win32_NetworkAdapterConfiguration to collect information for your computer. Use Get-Member to identify properties available in these classes. Include:
    • Computer Name
    • Manufacturer
    • Model
    • RAM
    • User Name
    • IP Addresses (could have more than one)
    • MAC Addresses (could have more than one)
    • Any other information you would like to include
  3. Review Microsoft MSDN: Connecting to WMI Remotely Starting with Windows Vista and Microsoft MSDN: Connecting to WMI on a Remote Computer by Using Windows PowerShell. Enable remote WMI on one or more computers on your network. Create a script that uses Get-WmiObject with the -Computer parameter to extend the computer information script from above and gather information from remote computers on the network.
  4. Review Microsoft TechNet: Enable-PSRemoting and Microsoft TechNet: Running Remote Commands. Enable remote PowerShell on one or more computers on your network. Create a script that uses the Enter-PSSession cmdlet to enter a session on a remote computer and gather the same computer information from above. Identify situations in which PowerShell Remoting would be a better solution than Remote WMI.

Lesson Summary

[edit | edit source]
  • Systems management refers to enterprise-wide administration of distributed systems, including computer systems.[15]
  • Centralized management has a time and effort trade-off that is related to the size of the company, the expertise of the IT staff, and the amount of technology being used.[16]
  • Windows Management Instrumentation (WMI) is a set of extensions to the Windows Driver Model that provides an operating system interface through which instrumented components provide information and notification.[17]
  • WMI is Microsoft's implementation of the Web-Based Enterprise Management (WBEM) and Common Information Model (CIM) standards from the Distributed Management Task Force (DMTF).[18]
  • WMI allows scripting languages like VBScript or Windows PowerShell to manage Microsoft Windows personal computers and servers, both locally and remotely, and is preinstalled in Windows 2000 and newer OSs.[19]
  • Most leading management-software packages are WMI-enabled and capable of consuming and providing WMI information through various user interfaces.[20]
  • WMI features include:[21]
    • Automation interfaces
    • .NET Management interfaces
    • C/C++ COM/DCOM programming interfaces
    • Remoting capabilities over DCOM and SOAP
    • Support for queries
    • Eventing capabilities
    • Code template generator
    • Predictability
    • Protects existing customer investments
    • Provides a logical and unified administration model
  • The Get-WmiObject cmdlet gets instances of WMI classes or information about the available WMI classes.[22]
  • The Win32_BIOS WMI class represents the attributes of the computer system's basic input/output services (BIOS) that are installed on a computer.[23]
  • The Win32_ComputerSystem class represents a computer system operating in a Windows environment.[24]
  • The Win32_NetworkAdapterConfiguration class represents the attributes and behaviors of a network adapter.[25]
  • The Get-Member cmdlet gets the members (properties and methods) of objects.[26] Object properties and methods may be accessed using . notation.
  • The netsh command enables and disables remote WMI traffic through the local Windows firewall.[27]
  • The Get-WmiObject cmdlet may be used to connect to remote computers using the -ComputerName parameter, with a specified Credential if necessary.[28]
  • The Enable-PSRemoting cmdlet configures the computer to receive Windows PowerShell remote commands that are sent by using the WS-Management technology.[29]
  • The Disable-PSRemoting cmdlet prevents users on other computers from running commands on the local computer.[30]
  • TrustedHosts allows a local computer to send authentication credentials to a remote computer in a non-domain environment. The Set-Item cmdlet is used to add a remote host to the TrustedHosts list.[31][32]
  • The Enter-PSSession cmdlet starts an interactive PowerShell session with a single remote computer. During the session, the commands that you type run on the remote computer, just as though you were typing directly on the remote computer. You can have only one interactive session at a time.[33]
  • The Exit-PSSession cmdlet ends interactive sessions that you started by using Enter-PSSession.[34]

Key Terms

[edit | edit source]
Common Information Model (CIM)
An open standard that defines how managed elements in an IT environment are represented as a common set of objects and relationships between them.[35]
Distributed Management Task Force (DMTF)
An organization of companies that collaborate on the development, validation and promotion of infrastructure management standards that enable effective management of IT environments.[36]
Web-Based Enterprise Management (WBEM)
A set of systems management technologies developed to unify the management of distributed computing environments.[37]
Windows Driver Model (WDM)
A framework for device drivers that was introduced with Windows 98 and Windows 2000 to replace the older VxD, and Windows NT Driver models.[38]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Systems management refers to _____.
Systems management refers to enterprise-wide administration of distributed systems, including computer systems.
2. Centralized management has a _____ that is related to _____.
Centralized management has a time and effort trade-off that is related to the size of the company, the expertise of the IT staff, and the amount of technology being used.
3. Windows Management Instrumentation (WMI) is _____.
Windows Management Instrumentation (WMI) is a set of extensions to the Windows Driver Model that provides an operating system interface through which instrumented components provide information and notification.
4. WMI is _____.
WMI is Microsoft's implementation of the Web-Based Enterprise Management (WBEM) and Common Information Model (CIM) standards from the Distributed Management Task Force (DMTF).
5. WMI allows _____ to _____, and is preinstalled in Windows _____ and newer OSs.
WMI allows scripting languages like VBScript or Windows PowerShell to manage Microsoft Windows personal computers and servers, both locally and remotely, and is preinstalled in Windows 2000 and newer OSs.
6. Most leading management-software packages are WMI-_____ and capable of _____.
Most leading management-software packages are WMI-enabled and capable of consuming and providing WMI information through various user interfaces.
7. WMI features include:
WMI features include:

Automation interfaces
.NET Management interfaces
C/C++ COM/DCOM programming interfaces
Remoting capabilities over DCOM and SOAP
Support for queries
Eventing capabilities
Code template generator
Predictability
Protects existing customer investments
Provides a logical and unified administration model

8. The Get-WmiObject cmdlet _____.
The Get-WmiObject cmdlet gets instances of WMI classes or information about the available WMI classes.
9. The Win32_BIOS WMI class _____.
The Win32_BIOS WMI class represents the attributes of the computer system's basic input/output services (BIOS) that are installed on a computer.
10. The Win32_ComputerSystem class _____.
The Win32_ComputerSystem class represents a computer system operating in a Windows environment.
11. The Win32_NetworkAdapterConfiguration class _____.
The Win32_NetworkAdapterConfiguration class represents the attributes and behaviors of a network adapter.
12. The Get-Member cmdlet _____.
The Get-Member cmdlet gets the members (properties and methods) of objects. Object properties and methods may be accessed using . notation.
13. The netsh command _____.
The netsh command enables and disables remote WMI traffic through the local Windows firewall.
14. The Get-WmiObject cmdlet _____.
The Get-WmiObject cmdlet may be used to connect to remote computers using the -ComputerName parameter, with a specified Credential if necessary.
15. The Enable-PSRemoting cmdlet _____.
The Enable-PSRemoting cmdlet configures the computer to receive Windows PowerShell remote commands that are sent by using the WS-Management technology.
16. The Disable-PSRemoting cmdlet _____.
The Disable-PSRemoting cmdlet prevents users on other computers from running commands on the local computer.
17. TrustedHosts allows a local computer to _____.
TrustedHosts allows a local computer to send authentication credentials to a remote computer in a non-domain environment.
18. The Set-Item cmdlet is used to _____.
The Set-Item cmdlet is used to add a remote host to the TrustedHosts list.
19. The Enter-PSSession cmdlet _____. During the session, the commands that you type _____. You can have _____ interactive session(s) at a time.
The Enter-PSSession cmdlet starts an interactive PowerShell session with a single remote computer. During the session, the commands that you type run on the remote computer, just as though you were typing directly on the remote computer. You can have only one interactive session at a time.
20. The Exit-PSSession cmdlet _____.
The Exit-PSSession cmdlet ends interactive sessions that you started by using Enter-PSSession.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.
  1. Microsoft TechNet:Get-WmiObject
  2. Microsoft MSDN: Win32_BIOS Class
  3. Microsoft MSDN: Operating System Classes
  4. Microsoft MSDN: Win32_NetworkAdapterConfiguration class
  5. Microsoft TechNet: Get-Member
  6. Microsoft MSDN: Connecting to WMI Remotely Starting with Windows Vista
  7. Microsoft MSDN: Connecting to WMI Remotely Starting with Windows Vista
  8. Microsoft MSDN: Connecting to WMI on a Remote Computer by Using Windows PowerShell
  9. Microsoft TechNet: Enable-PSRemoting
  10. Microsoft TechNet: Disable-PSRemoting
  11. Microsoft TechNet: Non-Domain Remoting
  12. Microsoft TechNet: Enable and Use Remote Commands in Windows PowerShell
  13. Microsoft TechNet: Enter-PSSession
  14. Microsoft TechNet: Exit-PSSession
  15. Wikipedia: Systems management
  16. Wikipedia: Systems management
  17. Wikipedia: Windows Management Instrumentation
  18. Wikipedia: Windows Management Instrumentation
  19. Wikipedia: Windows Management Instrumentation
  20. Wikipedia: Windows Management Instrumentation
  21. Wikipedia: Windows Management Instrumentation
  22. Microsoft TechNet:Get-WmiObject
  23. Microsoft MSDN: Win32_BIOS Class
  24. Microsoft MSDN: Operating System Classes
  25. Microsoft MSDN: Win32_NetworkAdapterConfiguration class
  26. Microsoft TechNet: Get-Member
  27. Microsoft MSDN: Connecting to WMI Remotely Starting with Windows Vista
  28. Microsoft MSDN: Connecting to WMI on a Remote Computer by Using Windows PowerShell
  29. Microsoft TechNet: Enable-PSRemoting
  30. Microsoft TechNet: Disable-PSRemoting
  31. Microsoft TechNet: Non-Domain Remoting
  32. Microsoft TechNet: Enable and Use Remote Commands in Windows PowerShell
  33. Microsoft TechNet: Enter-PSSession
  34. Microsoft TechNet: Exit-PSSession
  35. Wikipedia: Common Information Model (computing)
  36. Wikipedia: Distributed Management Task Force
  37. Wikipedia: Web-Based Enterprise Management
  38. Wikipedia: Windows Driver Model

Lesson 14 - Events

[edit | edit source]

This lesson introduces PowerShell event log processing.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic PowerShell event concepts.
  • Create PowerShell scripts to process events.

Readings

[edit | edit source]
  1. Wikipedia: Event Viewer
  2. Microsoft Support: How to View and Manage Event Logs in Event Viewer
  3. BonusBits: Mastering PowerShell Chapter 17 - Processes, Services, Event Logs

Multimedia

[edit | edit source]
  1. YouTube: Manage Event Logs From The Event Viewer to Find Windows 7 Related Problems
  2. YouTube: How to look for Unexpected Shutdown/User Restarts/BSOD using powershell and get-eventlog

Examples

[edit | edit source]

Get-EventLog

[edit | edit source]

The Get-EventLog cmdlet gets events and event logs on local and remote computers. Get-EventLog works only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.[1]

Get-EventLog -LogName System -EntryType Error -After (Get-Date).AddDays(-30)

Get-WinEvent

[edit | edit source]

The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs, and the event logs that are generated by the Windows Event Log technology introduced in Windows Vista.[2]

Get-WinEvent -FilterHashTable @{LogName='System'; Level=2; StartTime=(Get-Date).AddDays(-30)}

Selecting Event Properties

[edit | edit source]

The Select-Object cmdlet may be used to select specific event properties, and rename them as desired.[3]

$events = Get-WinEvent -FilterHashTable @{LogName='System'; Level=2; StartTime=(Get-Date).AddDays(-30)}
$events | Select-Object @{Name='Time';Expression={$_.'TimeCreated'}},
    @{Name="Source";Expression={$_.'ProviderName'}},
    @{Name="Event";Expression={$_.'Id'}}

New-EventLog

[edit | edit source]

The New-EventLog cmdlet creates a new classic event log on a local or remote computer. It can also register an event source that writes to the new log or to an existing log.[4]

New-EventLog -LogName 'PowerShell Scripts' -Source 'My Script'

Write-EventLog

[edit | edit source]

The Write-EventLog cmdlet writes an event to an event log.[5]

$message = 'Event log entry created by PowerShell script.'
Write-EventLog -LogName 'PowerShell Scripts' -Source 'My Script' -EntryType Information -EventId '1' -Category 0 -Message $message

Show-EventLog

[edit | edit source]

The Show-EventLog cmdlet opens Event Viewer on the local computer and displays in it all of the classic event logs on the local computer or a remote computer.[6]

Show-EventLog

Limit-EventLog

[edit | edit source]

The Limit-EventLog cmdlet sets the maximum size of a classic event log, how long each event must be retained, and what happens when the log reaches its maximum size.[7]

Limit-EventLog -LogName 'PowerShell Scripts' -MaximumSize 1MB

Clear-EventLog

[edit | edit source]

The Clear-EventLog cmdlet deletes all of the entries from the specified event logs on the local computer or on remote computers.[8]

Clear-EventLog -LogName 'PowerShell Scripts'

Remove-EventLog

[edit | edit source]

The Remove-EventLog cmdlet deletes an event log file from a local or remote computer and unregisters all of its event sources for the log. CAUTION: This cmdlet can delete operating system event logs, which might result in application failures and unexpected system behavior.[9]

Remove-EventLog -LogName 'PowerShell Scripts' -Confirm

Activities

[edit | edit source]
  1. Review Microsoft TechNet: Processing Event Logs in PowerShell. Create a script that uses Get-WinEvent to retrieve Windows events:
    • Filter events to select both warning and error events (levels 2 and 3) for the previous 24 hours (1 day).
    • Use Format-List * to see all available event properties and their default names. For the script, select only the properties for Level, Time, Source, Event, Task, and Message and label them accordingly.
    • Use Sort-Object to sort the events in ascending order by time.
    • Use Format-List to format the events as a list and then use Out-String to format the output so that it does not exceed 100 characters in width.
  2. Review Microsoft TechNet: Use PowerShell to Create and to Use a New Event Log and How to Use PowerShell to Write to Event Logs. Create a script that uses a new event log:
    • Use New-EventLog to create a new event log and event source.
    • Use Write-EventLog to add an event to the new event log.
    • Use Limit-EventLog to limit the size of the new event log to 1MB.
    • Use Show-EventLog to view the new log and event in the Event Viewer. View properties for the log to verify the size limit.
  3. Review Microsoft TechNet: PowerShell.exe Command-Line Help and Microsoft TechNet: Trigger a PowerShell Script from a Windows Event. Create a script that responds to an event:
    • Create a new script with a single line of Show-EventLog. Save the file with a simple path and filename, such as c:\Events.ps1.
    • Run the Events.ps1 script to verify that it opens the Event Viewer. View the new log and event in the Event Viewer.
    • In Event Viewer use Attach Task to This Event to start PowerShell.exe with the arguments -file C:\Events.ps1 to run your script when the event occurs.
    • Open Task Scheduler and confirm that your task has been added to Event Viewer Tasks in the Task Scheduler Library.
    • Close Event Viewer.
    • Use Write-Event to add the same event to the event log again. Confirm that the event causes Event Viewer to be displayed.
    • Use Clear-EventLog to clear the event log. Refresh the view in Event Viewer to confirm that the log was cleared.
    • Use Remove-EventLog to remove the event log. Be sure to use the -Confirm option to confirm which log is being removed, and then refresh the view in Event Viewer to confirm that the log was removed.
    • Clean up by using Task Scheduler to delete the Event Viewer Task and using Windows Explorer to delete the C:\Events.ps1 script file.

Lesson Summary

[edit | edit source]
  • Event Viewer lets administrators and users view the event logs on a local or remote Windows computer.[10]
  • Applications and operating-system components can use the centralized event log service to report events that have taken place.[11]
  • Event logs can be remotely viewed from other computers and multiple event logs can be centrally logged and monitored agentlessly and managed from a single computer.[12]
  • Events can also be directly associated with tasks, which run in the Task Scheduler and trigger automated actions when particular events take place.[13]
  • The Get-EventLog cmdlet gets events and event logs on local and remote computers. Get-EventLog works only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.[14]
  • The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs, and the event logs that are generated by the Windows Event Log technology introduced in Windows Vista.[15]
  • The Select-Object cmdlet may be used to select specific event properties, and rename them as desired.[16]
  • The New-EventLog cmdlet creates a new classic event log on a local or remote computer. It can also register an event source that writes to the new log or to an existing log.[17]
  • The Write-EventLog cmdlet writes an event to an event log.[18]
  • The Show-EventLog cmdlet opens Event Viewer on the local computer and displays in it all of the classic event logs on the local computer or a remote computer.[19]
  • The Limit-EventLog cmdlet sets the maximum size of a classic event log, how long each event must be retained, and what happens when the log reaches its maximum size.[20]
  • The Clear-EventLog cmdlet deletes all of the entries from the specified event logs on the local computer or on remote computers.[21]
  • The Remove-EventLog cmdlet deletes an event log file from a local or remote computer and unregisters all of its event sources for the log.[22]
  • The PowerShell.exe command-line parameter -File <script> runs the specified script.[23]

Key Terms

[edit | edit source]
Task Scheduler
A component of Microsoft Windows that provides the ability to schedule the launch of programs or scripts at pre-defined times or after specified time intervals.[24]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Event Viewer _____.
Event Viewer lets administrators and users view the event logs on a local or remote Windows computer.
2. Applications and operating-system components can use the centralized event log service to _____.
Applications and operating-system components can use the centralized event log service to report events that have taken place.
3. Event logs can be _____ from other computers and multiple event logs can be _____ from a single computer.
Event logs can be remotely viewed from other computers and multiple event logs can be centrally logged and monitored agentlessly and managed from a single computer.
4. Events can be directly associated with _____, which _____.
Events can be directly associated with tasks, which run in the Task Scheduler and trigger automated actions when particular events take place.
5. The Get-EventLog cmdlet _____.
The Get-EventLog cmdlet gets events and event logs on local and remote computers.
6. Get-EventLog works only on _____.
Get-EventLog works only on classic event logs.
7. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use _____.
To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.
8. The Get-WinEvent cmdlet _____.
The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs, and the event logs that are generated by the Windows Event Log technology introduced in Windows Vista.
9. The Select-Object cmdlet _____.
The Select-Object cmdlet may be used to select specific event properties, and rename them as desired.
10. The New-EventLog cmdlet _____.
The New-EventLog cmdlet creates a new classic event log on a local or remote computer. It can also register an event source that writes to the new log or to an existing log.
11. The Write-EventLog cmdlet _____.
The Write-EventLog cmdlet writes an event to an event log.
12. The Show-EventLog cmdlet _____.
The Show-EventLog cmdlet opens Event Viewer on the local computer and displays in it all of the classic event logs on the local computer or a remote computer.
13. The Limit-EventLog cmdlet _____.
The Limit-EventLog cmdlet sets the maximum size of a classic event log, how long each event must be retained, and what happens when the log reaches its maximum size.
14. The Clear-EventLog cmdlet _____.
The Clear-EventLog cmdlet deletes all of the entries from the specified event logs on the local computer or on remote computers.
15. The Remove-EventLog cmdlet _____.
The Remove-EventLog cmdlet deletes an event log file from a local or remote computer and unregisters all of its event sources for the log.
16. The PowerShell.exe command-line parameter _____ runs the specified script.
The PowerShell.exe command-line parameter -File <script> runs the specified script.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.

Lesson 15 - Objects

[edit | edit source]

This lesson introduces additional PowerShell topics, including custom objects, web requests, email, and Active Directory users and groups.

Objectives and Skills

[edit | edit source]

After completing this lesson, you will be able to:

  • Describe basic PowerShell object concepts.
  • Create PowerShell scripts to work with .NET library objects.
  • Create PowerShell scripts to work with COM objects.
  • Create PowerShell scripts to retrieve web pages.
  • Create PowerShell scripts to send email.
  • Create PowerShell scripts to manage Active Directory users and groups.

Readings

[edit | edit source]
  1. Wikipedia: Object (computer science)
  2. Wikipedia: Hypertext Transfer Protocol
  3. Wikipedia: Simple Mail Transfer Protocol
  4. Wikipedia: Active Directory
  5. BonusBits: Mastering PowerShell Chapter 6 - Using Objects

Multimedia

[edit | edit source]
  1. YouTube: PowerShell Fundamentals - Working with Objects
  2. YouTube: PowerShell Filtering Functions and Custom Objects
  3. YouTube: Manipulate Excel Workbooks and Worksheets with Powershell
  4. YouTube: Logging Into webpage with Invoke-WebRequest
  5. YouTube: Send an Email From PowerShell
  6. YouTube: User Account Mgmt Using PowerShell

Examples

[edit | edit source]

New-Object

[edit | edit source]

The New-Object cmdlet creates an instance of a .NET Framework or COM object.[1]

$ping = New-Object System.Net.NetworkInformation.Ping
$ping.Send('8.8.8.8')

PowerShell custom objects are created using the .NET PSObject class.[2]

$bios = Get-WmiObject -Class Win32_BIOS
$computer = Get-WmiObject -Class Win32_ComputerSystem

$object = New-Object PSObject
$object | Add-Member -MemberType NoteProperty -Name 'Computer Name' -Value $bios.PSComputerName
$object | Add-Member -MemberType NoteProperty -Name 'Manufacturer' -Value $bios.Manufacturer
$object | Add-Member -MemberType NoteProperty -Name 'Model' -Value $computer.Model
$object | Add-Member -MemberType NoteProperty -Name 'BIOS Version' -Value $bios.SMBIOSBIOSVersion
$object | Add-Member -MemberType NoteProperty -Name 'RAM' -Value $computer.TotalPhysicalMemory

$object | Out-GridView

Microsoft Excel is accessed as a COM object using Excel.Application.[3]

$excel = New-Object -COMObject Excel.Application
$excel.Visible = $true
$excel.Workbooks.Add()
$excel.ActiveSheet.Cells.Item(1, 1) = 'Hello Excel!'

Invoke-WebRequest

[edit | edit source]

The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service.[4]

$object = Invoke-WebRequest 'https://en.wikiversity.org/wiki/Windows_PowerShell'
$object.Content

Send-MailMessage

[edit | edit source]

The Send-MailMessage cmdlet sends an email message.[5]

$server = 'smtp.gmail.com'
$port = 587
$username = 'username'
$password = 'password'

$from = 'me@domain'
$to = 'you@domain'
$subject = 'PowerShell Email Test'
$body = 'Hello from PowerShell!'

$credential = New-Object System.Management.Automation.PSCredential($username, (ConvertTo-SecureString $password -AsPlainText -Force))

Send-MailMessage -From $from -To $to -Subject $subject -Body $body -SmtpServer $server -Port $port -Credential $credential -UseSsl

Import-Module

[edit | edit source]

The Import-Module cmdlet adds one or more modules to the current session.[6][7]

Import-Module ActiveDirectory

New-ADUser

[edit | edit source]

The New-ADUser cmdlet creates a new Active Directory user.[8]

$path = 'OU=test,DC=domain,DC=local'
$name = 'Display Name'
$username = 'username'
$password = 'password'

$password = ConvertTo-SecureString $password -AsPlainText -force
New-ADUser -Path $path -SamAccountName $username -Name $name -AccountPassword $password -Enabled $true

Get-ADUser

[edit | edit source]

The Get-ADUser cmdlet gets a user object or performs a search to retrieve multiple user objects.[9]

$user = Get-ADUser 'username'

Set-ADUser

[edit | edit source]

The Set-ADUser cmdlet modifies the properties of an Active Directory user.[10]

Set-ADUser -Identity 'username' -Enabled $false

Remove-ADUser

[edit | edit source]

The Remove-ADUser cmdlet removes an Active Directory user.[11]

Remove-ADUser -Identity 'username'

New-ADGroup

[edit | edit source]

The New-ADGroup cmdlet creates a new Active Directory group object.[12]

$path = 'OU=test,DC=domain,DC=local'
New-ADGroup -Path $path -Name 'Group Name' -GroupScope Global

Remove-ADGroup

[edit | edit source]

The Remove-ADGroup cmdlet removes an Active Directory group object.[13]

Remove-ADGroup -Identity 'Group Name'

Add-ADGroupMember

[edit | edit source]

The Add-ADGroupMember cmdlet adds one or more users, groups, service accounts, or computers as new members of an Active Directory group.[14]

Add-ADGroupMember -Identity 'Group Name' -Members 'username'

Remove-ADGroupMember

[edit | edit source]

The Remove-ADGroupMember cmdlet removes one or more users, groups, service accounts, or computers from an Active Directory group.[15]

Remove-ADGroupMember -Identity 'Group Name' -Members 'username'

Activities

[edit | edit source]
  1. Review Microsoft TechNet: Use PowerShell for Network Host and Port Discovery Sweeps. Use a for loop and the System.Net.NetworkInformation.Ping object to loop through your entire subnet and create an array of IP addresses on the subnet that respond to ping. Use Arp to identify hosts on the network that responded to the Arp request but blocked a ping response and add those hosts to the array. Then display the array.
  2. Review WindowsITPro: PowerShell Basics: Custom Objects. Create a script that uses Get-WmiObject to retrieve multiple computer properties and add those properties to a custom PSObject. Create an array of custom PSObject objects, with a separate object for each of several computers on the network. Pipe the array through Out-GridView to display the combined results.
  3. Review Learn PowerShell: PowerShell and Excel. Create a script that uses the Excel.Application COM object and nested for loops to generate a 10 x 10 multiplication table in the first worksheet in a new Excel workbook.
  4. Review Microsoft TechNet: Use PowerShell to Download Web Page Links from a Blog. Create a script that uses Invoke-WebRequest to download all links from https://en.wikiversity.org/wiki/Windows_PowerShell . Create an array of the links on the page. Use a recursive function so that the script also lists the links of any subpages of the page. Display the results using Out-GridView.
  5. Create a script to email all warning and error events from the previous 24 hours as a formatted list. Use the computer name in the from address, and include the current date in the subject. Use Task Scheduler to schedule the script to run daily at a given time, such as 6 a.m.
  6. Review Microsoft MSDN: Active Directory Module for Windows PowerShell – Quick start guide. Create a text file that lists 10 new users and the department they will work for in username, department format. Use Get-Content to read the file, New-ADUser to add the user, and Add-ADGroupMember to add the user to their department. Departments can be created manually or using New-ADGroup. Open Active Directory Users and Computers to confirm the users were created and added to their respective groups.

Lesson Summary

[edit | edit source]
  • An object is a location in memory having a value and possibly referenced by an identifier.[16]
  • The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems, and is the foundation of data communication for the World Wide Web.[17]
  • HTTP functions as a request-response protocol in the client-server computing model. The client submits an HTTP request message to the server. The server, which provides resources such as HTML files and other content, or performs other functions on behalf of the client, returns a response message to the client. The response contains completion status information about the request and may also contain requested content in its message body.[18]
  • Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (e-mail) transmission.[19]
  • SMTP by default uses TCP port 25. The protocol for mail submission is the same, but uses port 587.[20]
  • While electronic mail servers and other mail transfer agents use SMTP to send and receive mail messages, user-level client mail applications typically use SMTP only for sending messages to a mail server for relaying. For receiving messages, client applications usually use either POP3 or IMAP.[21]
  • Active Directory (AD) is a directory service that Microsoft developed for Windows domain networks and is included in most Windows Server operating systems as a set of processes and services.[22]
  • An Active Directory domain controller authenticates and authorizes all users and computers in a Windows domain type network.[23]
  • An Active Directory structure is an arrangement of information about objects. The objects fall into two broad categories: resources (e.g., printers) and security principals (user or computer accounts and groups).[24]
  • The New-Object cmdlet creates an instance of a .NET Framework or COM object.[25]
  • PowerShell custom objects are created using the .NET PSObject class.[26]
  • Microsoft Excel is accessed as a COM object using Excel.Application.[27]
  • The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service.[28]
  • The Send-MailMessage cmdlet sends an email message.[29]
  • The Import-Module cmdlet adds one or more modules to the current session.[30]
  • The New-ADUser cmdlet creates a new Active Directory user.[31]
  • The Get-ADUser cmdlet gets a user object or performs a search to retrieve multiple user objects.[32]
  • The Set-ADUser cmdlet modifies the properties of an Active Directory user.[33]
  • The Remove-ADUser cmdlet removes an Active Directory user.[34]
  • The New-ADGroup cmdlet creates a new Active Directory group object.[35]
  • The Remove-ADGroup cmdlet removes an Active Directory group object.[36]
  • The Add-ADGroupMember cmdlet adds one or more users, groups, service accounts, or computers as new members of an Active Directory group.[37]
  • The Remove-ADGroupMember cmdlet removes one or more users, groups, service accounts, or computers from an Active Directory group.[38]

Key Terms

[edit | edit source]
Component Object Model (COM)
A binary-interface standard for software components introduced by Microsoft in 1993, which is used to enable inter-process communication and dynamic object creation in a large range of programming languages.[39]
HTML (HyperText Markup Language)
The standard markup language used to create web pages.[40]
Post Office Protocol (POP)
An application-layer Internet standard protocol used by local e-mail clients to retrieve e-mail from a remote server over a TCP/IP connection.[41]
Internet Message Access Protocol (IMAP)
A protocol for e-mail retrieval and storage which specifically allows multiple clients simultaneously connected to the same mailbox.[42]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. An object is _____.
An object is a location in memory having a value and possibly referenced by an identifier.
2. The Hypertext Transfer Protocol (HTTP) is _____.
The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems, and is the foundation of data communication for the World Wide Web.
3. HTTP functions as a _____ protocol in the client-server computing model. The client submits _____ to the server. The server _____ to the client.
HTTP functions as a request-response protocol in the client-server computing model. The client submits an HTTP request message to the server. The server, which provides resources such as HTML files and other content, or performs other functions on behalf of the client, returns a response message to the client.
4. The HTTP response contains _____.
The HTTP response contains completion status information about the request and may also contain requested content in its message body.
5. Simple Mail Transfer Protocol (SMTP) is _____.
Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (e-mail) transmission.
6. SMTP by default uses TCP port _____. The protocol for mail submission is the same, but uses port _____.
SMTP by default uses TCP port 25. The protocol for mail submission is the same, but uses port 587.
7. While electronic mail servers and other mail transfer agents use SMTP to send and receive mail messages, user-level client mail applications typically use SMTP only for _____. For receiving messages, client applications usually use either _____ or _____.
While electronic mail servers and other mail transfer agents use SMTP to send and receive mail messages, user-level client mail applications typically use SMTP only for sending messages to a mail server for relaying. For receiving messages, client applications usually use either POP3 or IMAP.
8. Active Directory (AD) is _____ and is included in _____ as _____.
Active Directory (AD) is a directory service that Microsoft developed for Windows domain networks and is included in most Windows Server operating systems as a set of processes and services.
9. An Active Directory domain controller _____.
An Active Directory domain controller authenticates and authorizes all users and computers in a Windows domain type network.
10. An Active Directory structure is _____.
An Active Directory structure is an arrangement of information about objects.
11. Active Directory objects fall into two broad categories: _____.
Active Directory objects fall into two broad categories: resources (e.g., printers) and security principals (user or computer accounts and groups).
12. The New-Object cmdlet _____.
The New-Object cmdlet creates an instance of a .NET Framework or COM object.
13. PowerShell custom objects are created using _____.
PowerShell custom objects are created using the .NET PSObject class.
14. Microsoft Excel is accessed as _____.
Microsoft Excel is accessed as a COM object using Excel.Application.
15. The Invoke-WebRequest cmdlet _____.
The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service.
16. The Send-MailMessage cmdlet _____.
The Send-MailMessage cmdlet sends an email message.
17. The Import-Module cmdlet _____.
The Import-Module cmdlet adds one or more modules to the current session.
18. The New-ADUser cmdlet _____.
The New-ADUser cmdlet creates a new Active Directory user.
19. The Get-ADUser cmdlet _____.
The Get-ADUser cmdlet gets a user object or performs a search to retrieve multiple user objects.
20. The Set-ADUser cmdlet _____.
The Set-ADUser cmdlet modifies the properties of an Active Directory user.
21. The Remove-ADUser cmdlet _____.
The Remove-ADUser cmdlet removes an Active Directory user.
22. The New-ADGroup cmdlet _____.
The New-ADGroup cmdlet creates a new Active Directory group object.
23. The Remove-ADGroup cmdlet _____.
The Remove-ADGroup cmdlet removes an Active Directory group object.
24. The Add-ADGroupMember cmdlet _____.
The Add-ADGroupMember cmdlet adds one or more users, groups, service accounts, or computers as new members of an Active Directory group.
25. The Remove-ADGroupMember cmdlet _____.
The Remove-ADGroupMember cmdlet removes one or more users, groups, service accounts, or computers from an Active Directory group.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.
  1. Microsoft TechNet: New-Object
  2. WindowsITPro: PowerShell Basics: Custom Objects
  3. Learn PowerShell: PowerShell and Excel
  4. Microsoft TechNet: Invoke-WebRequest
  5. Microsoft TechNet: Send-MailMessage
  6. Microsoft TechNet: Import-Module
  7. Microsoft TechNet: Active Directory Administration with Windows PowerShell
  8. Microsoft TechNet: New-ADUser
  9. Microsoft TechNet: Get-ADUser
  10. Microsoft TechNet: Set-ADUser
  11. Microsoft TechNet: Remove-ADUser
  12. Microsoft TechNet: New-ADGroup
  13. Microsoft TechNet: Remove-ADGroup
  14. Microsoft TechNet: Add-ADGroupMember
  15. Microsoft TechNet: Remove-ADGroupMember
  16. Wikipedia: Object (computer science)
  17. Wikipedia: Hypertext Transfer Protocol
  18. Wikipedia: Hypertext Transfer Protocol
  19. Wikipedia: Simple Mail Transfer Protocol
  20. Wikipedia: Simple Mail Transfer Protocol
  21. Wikipedia: Simple Mail Transfer Protocol
  22. Wikipedia: Active Directory
  23. Wikipedia: Active Directory
  24. Wikipedia: Active Directory
  25. Microsoft TechNet: New-Object
  26. WindowsITPro: PowerShell Basics: Custom Objects
  27. Learn PowerShell: PowerShell and Excel
  28. Microsoft TechNet: Invoke-WebRequest
  29. Microsoft TechNet: Send-MailMessage
  30. Microsoft TechNet: Import-Module
  31. Microsoft TechNet: New-ADUser
  32. Microsoft TechNet: Get-ADUser
  33. Microsoft TechNet: Set-ADUser
  34. Microsoft TechNet: Remove-ADUser
  35. Microsoft TechNet: New-ADGroup
  36. Microsoft TechNet: Remove-ADGroup
  37. Microsoft TechNet: Add-ADGroupMember
  38. Microsoft TechNet: Remove-ADGroupMember
  39. Wikipedia: Component Object Model
  40. Wikipedia: HTML
  41. Wikipedia: Post Office Protocol
  42. Wikipedia: Internet Message Access Protocol