PowerShell/Collection
PowerShell
editLearning Guide
editThis learning guide supports the Wikiversity course PowerShell, available at http://en.wikiversity.org/wiki/PowerShell.
Overview
editPart 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
editMany 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
editThis is a third-semester, college-level course. Learners should already be familiar with introductory computer concepts and computer support concepts.
Resources
editThe 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
editExamples
editSee Also
editBibliography
editReferences
editLesson 1 - Introduction
editThis 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
editAfter 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
editMultimedia
editExamples
editGet-Help
editThe Get-Help cmdlet displays information about Windows PowerShell commands and concepts.[1]
Get-Help
Get-Host
editThe 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
editThe Update-Help cmdlet downloads and installs the newest help files on your computer.[3]
Update-Help
Activities
edit- Review Microsoft: Windows PowerShell. Identify the different resources available to learn and use PowerShell, and the different versions of PowerShell available for download.
- 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.
- Review Microsoft MSDN: Starting Windows PowerShell. Start PowerShell. Then start PowerShell ISE. Compare the two PowerShell environments.
- 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.
- 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.
- 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
- Review Microsoft: Windows PowerShell Quick Reference. Download the reference and print or save it for future use.
Lesson Summary
edit- 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- 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
editAssessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet: Get-Help
- ↑ Microsoft TechNet: Get-Host
- ↑ Microsoft TechNet: Update-Help
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia: Windows PowerShell
- ↑ Wikipedia:CMD.EXE
- ↑ Wikipedia: Component Object Model
- ↑ Wikipedia:COMMAND.COM
- ↑ Wikipedia: Compiler
- ↑ Wikipedia: Command-line interface
- ↑ Microsoft TechNet: Using the Get-Help Cmdlet
- ↑ Microsoft TechNet: Get-Host
- ↑ Wikipedia: Interpreted language
- ↑ Wikipedia: .NET Framework
- ↑ Wikipedia: Pipeline (computing)
- ↑ Wikipedia: Scripting language
- ↑ Wikipedia: Shell (computing)
- ↑ Microsoft TechNet: Update-Help
- ↑ Wikipedia: Windows Management Instrumentation
- ↑ Wikipedia: Windows Script Host
Lesson 2 - Console
editThis lesson introduces the PowerShell console by looking at cmdlets, the pipeline, and redirection.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editComments
editComments are added to a PowerShell script using the hashtag or number sign character (#).[1]
# This is a PowerShell comment.
Block Comments
editBlock comments are added to a PowerShell script using <# and #>.[2]
<#
This is a series or
block of comments.
#>
Get-Command
editThe Get-Command cmdlet lists all PowerShell commands.[3]
Get-Command # List all PowerShell commands.
Get-Date
editThe Get-Date cmdlet returns the current date and time.[4]
Get-Date # Get the current date and time.
Get-Process
editThe Get-Process cmdlet lists all running processes.[5]
Get-Process # List all running processes.
Get-Service
editThe Get-Service cmdlet lists all installed services.[6]
Get-Service # List all installed services.
Select-Object
editThe Select-Object cmdlet selects objects or object properties.[7]
Get-Host | Select-Object 'Name' # Displays the host's Name property only.
Sort-Object
editThe Sort-Object cmdlet sorts objects based on property values.[8]
Get-Service | Sort-Object 'Status' # Displays services sorted by Status.
Where-Object
editThe 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
editThe > 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- Experiment with customizing the PowerShell console properties, including font, screen buffer size, and colors.
- 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.
- Use the Get-Host and Select-Object cmdlets and the pipeline to select the PowerShell version number.
- 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.
- 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).
- 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- 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- 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
editAssessments
edit- Flashcards: Quizlet: Windows PowerShell - Console
- Quiz: Quizlet: Windows PowerShell - Console
See Also
editReferences
edit- ↑ Wikipedia: Comparison of programming languages (syntax)
- ↑ Wikipedia: Comparison of programming languages (syntax)
- ↑ Microsoft TechNet: Get-Command
- ↑ Microsoft TechNet: Get-Date
- ↑ Microsoft TechNet: Get-Process
- ↑ Microsoft TechNet: Get-Service
- ↑ Microsoft TechNet: Select-Object
- ↑ Microsoft TechNet: Sort-Object
- ↑ Microsoft TechNet: Where-Object
- ↑ Microsoft TechNet: about_Redirection
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Command-line interface
- ↑ Wikipedia: Pipeline (Unix)
- ↑ Wikipedia: Pipeline (Unix)
- ↑ Wikipedia: Pipeline (Unix)
- ↑ Wikipedia: Redirection (computing)
- ↑ Wikipedia: Redirection (computing)
- ↑ Wikipedia: Redirection (computing)
- ↑ Wikipedia: Comment (computer programming)
- ↑ Wikipedia: Comparison of programming languages (syntax)
- ↑ Wikipedia: Comparison of programming languages (syntax)
- ↑ Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
- ↑ Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
- ↑ Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
- ↑ Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
- ↑ Master-PowerShell | With Dr. Tobias Weltner: Chapter 1. The PowerShell Console
- ↑ Microsoft TechNet: Get-Command
- ↑ Microsoft TechNet: Get-Date
- ↑ Microsoft TechNet: Get-Process
- ↑ Microsoft TechNet: Get-Service
- ↑ Microsoft TechNet: Select-Object
- ↑ Microsoft TechNet: Sort-Object
- ↑ Microsoft TechNet: Where-Object
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Data buffer
- ↑ Wikipedia: Default (computer science)
- ↑ Wikipedia: Delimiter
- ↑ Wikipedia: Environment variable
- ↑ Wikipedia: Escape character
- ↑ Wikipedia: Command-line option
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Pseudocode
- ↑ Wikipedia: Standard streams
- ↑ Wikipedia: Standard streams
- ↑ Wikipedia: Standard streams
- ↑ Wikipedia: Stream (computing)
Lesson 3 - ISE
editThis lesson introduces PowerShell ISE, the integrated scripting environment by examining the scripting environment, automatic code completion, and by creating simple scripts.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editGet-Alias
editThe Get-Alias cmdlet displays a list of current Windows PowerShell aliases.[1]
Get-Alias # List current aliases.
Get-ExecutionPolicy
editThe 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
editThe 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
editThe 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
editThe 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
editThe Write-Host cmdlet writes directly to the host environment, bypassing the pipeline.[6]
Write-Host 'Hello PowerShell!'
Write-Output
editThe Write-Output cmdlet writes to the pipeline.[7]
Write-Output 'Hello PowerShell!'
Comparing Write-Host and Write-Output
editWhen 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- 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.
- Review Microsoft TechNet: Using the Get-Alias Cmdlet. Display a list of all Windows PowerShell aliases.
- 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.
- 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.
- 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- 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
editReview Questions
editAssessments
edit- Flashcards: Quizlet: Windows PowerShell - ISE
- Quiz: Quizlet: Windows PowerShell - ISE
See Also
editReferences
edit- ↑ Microsoft TechNet: Get-Alias
- ↑ Microsoft TechNet: Get-ExecutionPolicy
- ↑ Microsoft TechNet: Set-ExecutionPolicy
- ↑ Microsoft TechNet: Start-Service
- ↑ Microsoft TechNet: Stop-Service
- ↑ Microsoft TechNet: Write-Host
- ↑ Microsoft TechNet: Write-Output
- ↑ Jeffrey Snover's blog: Write-Host Considered Harmful
- ↑ Wikipedia: Integrated development environment
- ↑ Wikipedia: Integrated development environment
- ↑ Wikipedia: Integrated development environment
- ↑ Microsoft TechNet: How to Use Tab Completion
- ↑ Microsoft TechNet: How to Use Tab Completion
- ↑ Microsoft TechNet: How to Create a PowerShell Tab in Windows PowerShell ISE
- ↑ Microsoft TechNet: How to Create a PowerShell Tab in Windows PowerShell ISE
- ↑ Microsoft TechNet: How to Use the Console Pane in the Windows PowerShell ISE
- ↑ Microsoft TechNet: How to Use the Console Pane in the Windows PowerShell ISE
- ↑ Microsoft TechNet: How to Use the Console Pane in the Windows PowerShell ISE
- ↑ Microsoft TechNet: How to Write and Run Scripts in the Windows PowerShell ISE
- ↑ Microsoft TechNet: How to Debug Scripts in Windows PowerShell ISE
- ↑ Microsoft TechNet: How to Use Profiles in Windows PowerShell ISE
- ↑ PowerShell.com: Master-PowerShell | With Dr. Tobias Weltner - Chapter 2. Interactive PowerShell
- ↑ Microsoft TechNet: Get-Alias
- ↑ Microsoft TechNet: Get-ExecutionPolicy
- ↑ Microsoft TechNet: Set-ExecutionPolicy
- ↑ Microsoft TechNet: Start-Service
- ↑ Microsoft TechNet: Stop-Service
- ↑ Microsoft TechNet: Write-Host
- ↑ Microsoft TechNet: Write-Output
- ↑ Wikipedia: Breakpoint
- ↑ Wikipedia: Debugging
Lesson 4 - Variables
editThis lesson introduces PowerShell variables, constants, and data types.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editData Types
editPowerShell 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
editVariables 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
editSingle 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
editThe 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- 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.
- 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.
- 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.
- 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.
- 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- 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- 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
editAssessments
edit- Flashcards: Quizlet: Windows PowerShell - Variables
- Quiz: Quizlet: Windows PowerShell - Variables
- Practice Tests: Variables
- Flashcards: Quizplus: Variables
See Also
editReferences
edit- ↑ 4sysops: The PowerShell variable – Naming, value, data type
- ↑ Microsoft Developer Network: Object.GetType Method
- ↑ Microsoft TechNet: about_Quoting_Rules
- ↑ Microsoft TechNet: Read-Host
- ↑ Wikipedia: Variable (computer science)
- ↑ Wikipedia: Constant (computer programming)
- ↑ Wikipedia: Variable (computer science)
- ↑ Wikipedia: Variable (computer science)
- ↑ Wikipedia: Data type
- ↑ Wikipedia: Type conversion
- ↑ Wikipedia: Variable (computer science)
- ↑ Wikipedia: Scope (computer science)
- ↑ PowerShell.com: Master-PowerShell | With Dr. Tobias Weltner - Chapter 3. Variables
- ↑ PowerShell.com: Master-PowerShell | With Dr. Tobias Weltner - Chapter 3. Variables
- ↑ PowerShell.com: Master-PowerShell | With Dr. Tobias Weltner - Chapter 3. Variables
- ↑ Microsoft TechNet: about_Quoting_Rules
- ↑ Microsoft TechNet: Read-Host
- ↑ Wikipedia: ASCII
- ↑ Wikipedia: Bit
- ↑ Wikipedia: Boolean
- ↑ Wikipedia: Byte
- ↑ Wikipedia: Character (computing)
- ↑ Wikipedia: Floating point
- ↑ Wikipedia: Garbage collection (computer science)
- ↑ Wikipedia: Immutable object
- ↑ Wikipedia: Integer
- ↑ Wikipedia: Integer (computer science)
- ↑ Wikipedia: Memory leak
- ↑ Wikipedia: String (computer science)
- ↑ Wikipedia: Unicode
Lesson 5 - Expressions
editThis lesson introduces PowerShell expressions.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editArithmetic Operators
editArithmetic 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
editAssignment 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
editUnary operators increment or decrement a single variable by one.[3]
$a = 1
$a++ # a = 2
$a-- # a = 1
Comparison Operators
editComparison 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
editLogical 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
editString 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- 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.
- 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.
- 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.
- 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- 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- 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
editAssessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Wikipedia: Expression (computer science)
- ↑ Wikipedia: Statement (computer science)
- ↑ Wikipedia: Statement (computer science)
- ↑ Wikipedia: Order of operations
- ↑ Wikipedia: Order of operations
- ↑ Wikipedia: Order of operations
- ↑ Wikipedia: Order of operations
- ↑ Wikipedia: Unary operation
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Microsoft TechNet: about_Operators
- ↑ Wikipedia: Identifier
- ↑ Wikipedia: Modulo operation
- ↑ Wikipedia: Reserved word
Lesson 6 - Conditions
editThis lesson introduces PowerShell conditions, switch statements, and regular expressions.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editIf
editThe 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
editThe 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
editThe -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
editThe 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
editThe 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- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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- 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 theELSE
block (which is usually optional), or if there is noELSE
branch, then after theEND 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
andelse
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- 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
editIF (boolean condition) THEN
(consequent)
ELSE
(alternative)
END IF
if (<test1>)
{<statement list 1>}
elseif (<test2>)
{<statement list 2>}
else
{<statement list 3>}
switch (<test-value>)
{
<condition> {<statement list 1>}
<condition> {<statement list 2>}
...
default {<statement list 3>}
}
Assessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet: about_If
- ↑ Microsoft TechNet: about_Switch
- ↑ Microsoft MSDN: Validate a Zip+4 Zip Code
- ↑ Microsoft TechNet: about_PowerShell
- ↑ Microsoft TechNet: about_Break
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Microsoft TechNet: about_If
- ↑ Microsoft TechNet: about_If
- ↑ Microsoft TechNet: about_Comparison_Operators
- ↑ Microsoft Developer Network: Boolean Values and Operators
- ↑ Wikipedia: Switch statement
- ↑ Wikipedia: Switch statement
- ↑ Microsoft TechNet: about_Switch
- ↑ Microsoft TechNet: about_Switch
- ↑ Microsoft TechNet: about_Switch
- ↑ Microsoft TechNet: about_Break
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Spaghetti code
- ↑ Wikipedia: Structured programming
- ↑ Wikipedia: Whitespace character
Lesson 7 - Loops
editThis 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
editAfter 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- Wikipedia: Control flow
- BonusBits: Mastering PowerShell Chapter 8 - Loops
Multimedia
editExamples
editWhile
editThe 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
editThe 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
editThe 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)
For
editThe 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
editThe 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
editThe 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
editThe 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
editExit causes Windows PowerShell to exit a script or a Windows PowerShell instance.[8]
if(<some fatal error>)
{
Exit <optional return code>
}
Foreach-Object
editThe 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
editThe 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
editThe Get-Counter cmdlet gets performance counter data from local and remote computers.[11]
Get-Counter
Activities
edit- 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.
- 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.
- 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.
- 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.
- 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.
- 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- 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- 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
editAssessments
edit- Flashcards: Quizlet: Windows PowerShell - Loops
- Quiz: Quizlet: Windows PowerShell - Loops
See Also
editReferences
edit- ↑ Microsoft TechNet: about_While
- ↑ Microsoft TechNet: about_Do
- ↑ Microsoft TechNet: about_Do
- ↑ Microsoft TechNet: about_For
- ↑ Microsoft TechNet: about_ForEach
- ↑ Microsoft TechNet: about_Continue
- ↑ Microsoft TechNet: about_Break
- ↑ Microsoft TechNet: about_Language_Keywords
- ↑ Microsoft TechNet: ForEach-Object
- ↑ Microsoft TechNet: Using the Start-Sleep Cmdlet
- ↑ Microsoft TechNet: Get-Counter
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Microsoft TechNet: about_Language_Keywords
- ↑ Microsoft TechNet: ForEach-Object
- ↑ Microsoft TechNet: Using the Start-Sleep Cmdlet
- ↑ Microsoft TechNet: Get-Counter
- ↑ Wikipedia: Infinite loop
Lesson 8 - Arrays
editThis lesson introduces PowerShell arrays and hash tables.
Objectives and Skills
editAfter 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- Wikipedia: Array data type
- Wikipedia: Associative array
- BonusBits: Mastering PowerShell Chapter 4 - Arrays and Hashtables
Multimedia
editExamples
editInitializing an Array
edit$array=@(1,2,3,5,6,7,8);
Checking the Size of an Array
edit$array.Length
Accessing Array Elements
edit$array[0] + $array[1] + $array[2]
Initializing an Empty Array
edit$array = @()
Adding Elements to an Array
edit$array += 1
$array += 2
$array += 3
Removing Elements from an Array
editTo 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
editfor($i = 0; $i -lt $array.Length; $i++)
{
$array[$i]
}
Looping Through an Array Using a ForEach Loop
editforeach($element in $array)
{
$element
}
Multi-Dimensional Arrays
edit$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$pets = @{Cat = 'Frisky'; Dog = 'Spot'; Fish = 'Nimo'; Hamster = 'Whiskers'}
Accessing Hash Table Items
edit$pets.Cat # Frisky
$pets.Dog # Spot
$pets.Fish # Nimo
$pets.Hamster # Whiskers
Initializing an Empty Hash Table
edit$pets = @{}
Adding Items to a Hash Table
editEither:
$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$pets.Remove('Hamster')
Looping Through a Hash Table Using ForEach
editforeach($pet in $pets.keys)
{
$pet # Print each Key
$pets.$pet # Print value of each Key
}
Format-Table
editThe Format-Table cmdlet formats hash table output as a table.[1]
$pets | Format-Table
Format-List
editThe Format-List cmdlet formats hash table output as a list of separate key-value pairs.[2]
$pets | Format-List
Activities
edit- 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.
- 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.
- 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.
- 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.
- 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- 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- 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
editAssessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet: Format-Table
- ↑ Microsoft TechNet: Format-List
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Bounds checking
- ↑ Wikipedia: Hash table
- ↑ Wikipedia: Hash table
- ↑ Wikipedia: Associative array
- ↑ Microsoft TechNet: about_Arrays
- ↑ Microsoft TechNet: about_Arrays
- ↑ Microsoft TechNet: about_Arrays
- ↑ Microsoft TechNet: about_Arrays
- ↑ Microsoft TechNet: about_Arrays
- ↑ SS64: Arrays
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: about_Hash_Tables
- ↑ Microsoft TechNet: Format-Table
- ↑ Microsoft TechNet: Format-List
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Associative array
- ↑ Wikipedia: Hash table
- ↑ Wikipedia: Array data type
- ↑ Wikipedia: Key
Lesson 9 - Functions
editThis lesson introduces PowerShell functions.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editGet-Time
editGet-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
editGet-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
editBy 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
editPowerShell 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
editThe $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
editBy 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
editBy 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
editYou 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
editThe 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- 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.
- 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.
- 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.
- 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- 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- 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- 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
Assessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Ref
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Variables
- ↑ Microsoft TechNet: about_Variables
- ↑ Wikipedia: Factorial
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Ref
- ↑ Microsoft TechNet: about_Functions
- ↑ Microsoft TechNet: about_Functions
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Call stack
- ↑ Wikipedia: Iteration
- ↑ Wikipedia: Library (computing)
- ↑ Wikipedia: Method (computer programming)
- ↑ Wikipedia: Recursion (computer science)
Lesson 10 - Errors
editThis lesson introduces PowerShell debugging, error handling, and parameter validation.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editTry Catch
editUse 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
editfunction Get-Square()
{
Param
(
[double]$value
)
return $value * $value
}
Mandatory Validation
editThe Mandatory argument indicates that the parameter is required.[2]
function Get-Square()
{
Param
(
[parameter(Mandatory=$true)]
[double]$value
)
return $value * $value
}
Range Validation
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editError 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- 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.
- 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.
- 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.
- 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- 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- 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
editNormally 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.
Data type validation
Range and constraint validation
Code and cross-reference validation
Structured (advanced) validation
parameter(Mandatory=$true)
ValidateRange
ValidateNotNullOrEmpty
ValidateLength
ValidatePattern
ValidateScript
Assessments
edit- Flashcards: Quizlet: Windows PowerShell - Errors
- Quiz: Quizlet: Windows PowerShell - Errors
See Also
editReferences
edit- ↑ Microsoft TechNet: about_Try_Catch_Finally
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Wikipedia: Debugging
- ↑ Wikipedia: Debugging
- ↑ Wikipedia: Debugging
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Parameter validation
- ↑ Wikipedia: Data validation
- ↑ Wikipedia: Data validation
- ↑ Wikipedia: Data validation
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Wikipedia: Assertion (software development)
- ↑ Wikipedia: Debugger
- ↑ Wikipedia: Divide and conquer algorithm
- ↑ Wikipedia: Integration testing
- ↑ Wikipedia: Logfile
- ↑ Wikipedia: Mission critical
- ↑ Wikipedia: Core dump
- ↑ Wikipedia: Patch (computing)
- ↑ Wikipedia: Debugging
- ↑ Wikipedia: Profiling (computer programming)
- ↑ Wikipedia: Tracing (software)
- ↑ Wikipedia: Unit testing
- ↑ Wikipedia: Verification and validation (software)
Lesson 11 - File System
editThis lesson introduces PowerShell file system processing.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editGet-ChildItem
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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- Review Microsoft TechNet: Using the Get-ChildItem Cmdlet. Experiment with using Get-ChildItem to retrieve directory listings.
- Review Microsoft TechNet: Using the New-Item Cmdlet. Experiment with creating folders and files.
- Review Microsoft TechNet: Using the Move-Item Cmdlet. Experiment with moving folders and files.
- Review Microsoft TechNet: Using the Copy-Item Cmdlet. Experiment with copying folders and files.
- Review Microsoft TechNet: Using the Remove-Item Cmdlet. Experiment with removing folders and files.
- 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.
- 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- 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- 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
editAssessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet: Get-ChildItem
- ↑ Microsoft TechNet: New-Item
- ↑ Microsoft TechNet: Move-Item
- ↑ Microsoft TechNet: Copy-Item
- ↑ Microsoft TechNet: Remove-Item
- ↑ Microsoft TechNet: Test-Path
- ↑ Microsoft TechNet: Set-Content
- ↑ Microsoft TechNet: Add-Content
- ↑ Microsoft TechNet: Get-Content
- ↑ Microsoft TechNet: Clear-Content
- ↑ Wikipedia: File system
- ↑ Wikipedia: File system
- ↑ Wikipedia: File system
- ↑ Wikipedia: File system
- ↑ Wikipedia: File system
- ↑ Wikipedia: File system
- ↑ Wikipedia: File system
- ↑ Wikipedia: File system
- ↑ Wikipedia: File system
- ↑ Wikipedia: Directory (computing)
- ↑ Wikipedia: Text file
- ↑ Wikipedia: Text file
- ↑ Microsoft TechNet: Get-ChildItem
- ↑ Microsoft TechNet: New-Item
- ↑ Microsoft TechNet: Move-Item
- ↑ Microsoft TechNet: Copy-Item
- ↑ Microsoft TechNet: Remove-Item
- ↑ Microsoft TechNet: Test-Path
- ↑ Microsoft TechNet: Set-Content
- ↑ Microsoft TechNet: Add-Content
- ↑ Microsoft TechNet: Get-Content
- ↑ Microsoft TechNet: Clear-Content
- ↑ Wikipedia: ASCII
- ↑ Wikipedia: Metadata
- ↑ Wikipedia: File system fragmentation
- ↑ Wikipedia: File system
- ↑ Wikipedia: Directory (computing)
- ↑ Wikipedia: Metadata
- ↑ Wikipedia: Directory (computing)
- ↑ Wikipedia: Metadata
- ↑ Wikipedia: Directory (computing)
Lesson 12 - Registry
editThis lesson introduces PowerShell Registry processing.
Objectives and Skills
editAfter completing this lesson, you will be able to:
- Describe basic PowerShell Windows Registry concepts.
- Create PowerShell scripts to manage Registry keys.
Readings
edit- Wikipedia: Windows Registry
- Wikipedia: INI file
- BonusBits: Mastering PowerShell Chapter 16 - The Registry
Multimedia
editExamples
editGet-PSDrive
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe Remove-Item cmdlet deletes one or more items.[7]
$path = 'HKCU:\Software\Scripts\My Script'
Remove-Item -Path $path -Confirm
Remove-ItemProperty
editThe 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- 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.
- 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.
- 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.
- Review CrucialSecurityBlog: Typed URLs. Create a script that uses a foreach loop to display Internet Explorer history (Internet Explorer Typed Urls).
- 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.
- 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- 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- 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
editAssessments
edit- Flashcards: Quizlet: Windows PowerShell - Registry
- Quiz: Quizlet: Windows PowerShell - Registry
See Also
editReferences
edit- ↑ Microsoft TechNet:Get-PSDrive
- ↑ Microsoft TechNet: New-Item
- ↑ Microsoft TechNet: New-ItemProperty
- ↑ Microsoft TechNet: Get-Item
- ↑ Microsoft TechNet: Get-ItemProperty
- ↑ Microsoft TechNet: Set-ItemProperty
- ↑ Microsoft TechNet: Remove-Item
- ↑ Microsoft TechNet: Remove-ItemProperty
- ↑ Wikipedia: Windows Registry
- ↑ Wikipedia: Windows Registry
- ↑ Wikipedia: Windows Registry
- ↑ Wikipedia: Windows Registry
- ↑ Wikipedia: Windows Registry
- ↑ Wikipedia: Windows Registry
- ↑ Wikipedia: Windows Registry
- ↑ Wikipedia: Windows Registry
- ↑ Wikipedia: INI file
- ↑ Wikipedia: INI file
- ↑ Wikipedia: INI file
- ↑ Microsoft TechNet: Using the Get-PSDrive Cmdlet
- ↑ http://technet.microsoft.com/en-us/library/hh849796.aspx Microsoft TechNet:Get-PSDrive]
- ↑ Microsoft TechNet: New-Item
- ↑ Microsoft TechNet: New-ItemProperty
- ↑ Microsoft TechNet: Get-Item
- ↑ Microsoft TechNet: Get-ItemProperty
- ↑ Microsoft TechNet: Set-ItemProperty
- ↑ Microsoft TechNet: Remove-Item
- ↑ Microsoft TechNet: Remove-ItemProperty
- ↑ Microsoft MSDN: Registry Hives
Lesson 13 - WMI
editThis lesson introduces PowerShell systems management using Windows Management Instrumentation (WMI), Remote WMI, and PowerShell Remoting.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editGet-WmiObject List
editThe Get-WmiObject cmdlet gets instances of WMI classes or information about the available WMI classes.[1]
Get-WmiObject -List
Win32_BIOS
editThe 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
editThe 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
editThe Win32_NetworkAdapterConfiguration class represents the attributes and behaviors of a network adapter.[4]
Get-WmiObject -Class Win32_NetworkAdapterConfiguration
win32_logicaldisk
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe Disable-PSRemoting cmdlet prevents users on other computers from running commands on the local computer.[10]
Disable-PSRemoting -Force
Trusted Hosts
editTrustedHosts 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
editThe 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
editThe Exit-PSSession cmdlet ends interactive sessions that you started by using Enter-PSSession.[14]
Exit-PSSession
Activities
edit- 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.
- 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
- 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.
- 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- 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- 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
editAutomation 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
Assessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet:Get-WmiObject
- ↑ Microsoft MSDN: Win32_BIOS Class
- ↑ Microsoft MSDN: Operating System Classes
- ↑ Microsoft MSDN: Win32_NetworkAdapterConfiguration class
- ↑ Microsoft TechNet: Get-Member
- ↑ Microsoft MSDN: Connecting to WMI Remotely Starting with Windows Vista
- ↑ Microsoft MSDN: Connecting to WMI Remotely Starting with Windows Vista
- ↑ Microsoft MSDN: Connecting to WMI on a Remote Computer by Using Windows PowerShell
- ↑ Microsoft TechNet: Enable-PSRemoting
- ↑ Microsoft TechNet: Disable-PSRemoting
- ↑ Microsoft TechNet: Non-Domain Remoting
- ↑ Microsoft TechNet: Enable and Use Remote Commands in Windows PowerShell
- ↑ Microsoft TechNet: Enter-PSSession
- ↑ Microsoft TechNet: Exit-PSSession
- ↑ Wikipedia: Systems management
- ↑ Wikipedia: Systems management
- ↑ Wikipedia: Windows Management Instrumentation
- ↑ Wikipedia: Windows Management Instrumentation
- ↑ Wikipedia: Windows Management Instrumentation
- ↑ Wikipedia: Windows Management Instrumentation
- ↑ Wikipedia: Windows Management Instrumentation
- ↑ Microsoft TechNet:Get-WmiObject
- ↑ Microsoft MSDN: Win32_BIOS Class
- ↑ Microsoft MSDN: Operating System Classes
- ↑ Microsoft MSDN: Win32_NetworkAdapterConfiguration class
- ↑ Microsoft TechNet: Get-Member
- ↑ Microsoft MSDN: Connecting to WMI Remotely Starting with Windows Vista
- ↑ Microsoft MSDN: Connecting to WMI on a Remote Computer by Using Windows PowerShell
- ↑ Microsoft TechNet: Enable-PSRemoting
- ↑ Microsoft TechNet: Disable-PSRemoting
- ↑ Microsoft TechNet: Non-Domain Remoting
- ↑ Microsoft TechNet: Enable and Use Remote Commands in Windows PowerShell
- ↑ Microsoft TechNet: Enter-PSSession
- ↑ Microsoft TechNet: Exit-PSSession
- ↑ Wikipedia: Common Information Model (computing)
- ↑ Wikipedia: Distributed Management Task Force
- ↑ Wikipedia: Web-Based Enterprise Management
- ↑ Wikipedia: Windows Driver Model
Lesson 14 - Events
editThis lesson introduces PowerShell event log processing.
Objectives and Skills
editAfter completing this lesson, you will be able to:
- Describe basic PowerShell event concepts.
- Create PowerShell scripts to process events.
Readings
edit- Wikipedia: Event Viewer
- Microsoft Support: How to View and Manage Event Logs in Event Viewer
- BonusBits: Mastering PowerShell Chapter 17 - Processes, Services, Event Logs
Multimedia
editExamples
editGet-EventLog
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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- 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.
- 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.
- 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- 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- 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
editAssessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet: Get-EventLog
- ↑ Microsoft TechNet: Get-WinEvent
- ↑ Microsoft TechNet: Cool Pipeline Tricks, Redux
- ↑ Microsoft TechNet: New-EventLog
- ↑ Microsoft TechNet: Write-EventLog
- ↑ Microsoft TechNet: Show-EventLog
- ↑ Microsoft TechNet: Limit-EventLog
- ↑ Microsoft TechNet: Clear-EventLog
- ↑ Microsoft TechNet: Remove-EventLog
- ↑ Wikipedia: Event Viewer
- ↑ Wikipedia: Event Viewer
- ↑ Wikipedia: Event Viewer
- ↑ Wikipedia: Event Viewer
- ↑ Microsoft TechNet: Get-EventLog
- ↑ Microsoft TechNet: Get-WinEvent
- ↑ Microsoft TechNet: Cool Pipeline Tricks, Redux
- ↑ Microsoft TechNet: New-EventLog
- ↑ Microsoft TechNet: Write-EventLog
- ↑ Microsoft TechNet: Show-EventLog
- ↑ Microsoft TechNet: Limit-EventLog
- ↑ Microsoft TechNet: Clear-EventLog
- ↑ Microsoft TechNet: Remove-EventLog
- ↑ Microsoft TechNet: PowerShell.exe Command-Line Help
- ↑ Wikipedia: Windows Task Scheduler
Lesson 15 - Objects
editThis lesson introduces additional PowerShell topics, including custom objects, web requests, email, and Active Directory users and groups.
Objectives and Skills
editAfter 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
editMultimedia
edit- YouTube: PowerShell Fundamentals - Working with Objects
- YouTube: PowerShell Filtering Functions and Custom Objects
- YouTube: Manipulate Excel Workbooks and Worksheets with Powershell
- YouTube: Logging Into webpage with Invoke-WebRequest
- YouTube: Send an Email From PowerShell
- YouTube: User Account Mgmt Using PowerShell
Examples
editNew-Object
editThe 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
editThe 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
editThe 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
editThe Import-Module cmdlet adds one or more modules to the current session.[6][7]
Import-Module ActiveDirectory
New-ADUser
editThe 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
editThe Get-ADUser cmdlet gets a user object or performs a search to retrieve multiple user objects.[9]
$user = Get-ADUser 'username'
Set-ADUser
editThe Set-ADUser cmdlet modifies the properties of an Active Directory user.[10]
Set-ADUser -Identity 'username' -Enabled $false
Remove-ADUser
editThe Remove-ADUser cmdlet removes an Active Directory user.[11]
Remove-ADUser -Identity 'username'
New-ADGroup
editThe 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
editThe Remove-ADGroup cmdlet removes an Active Directory group object.[13]
Remove-ADGroup -Identity 'Group Name'
Add-ADGroupMember
editThe 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
editThe 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- 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.
- 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.
- 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.
- 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.
- 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.
- 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- 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- 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
editAssessments
editSee Also
editReferences
edit- ↑ Microsoft TechNet: New-Object
- ↑ WindowsITPro: PowerShell Basics: Custom Objects
- ↑ Learn PowerShell: PowerShell and Excel
- ↑ Microsoft TechNet: Invoke-WebRequest
- ↑ Microsoft TechNet: Send-MailMessage
- ↑ Microsoft TechNet: Import-Module
- ↑ Microsoft TechNet: Active Directory Administration with Windows PowerShell
- ↑ Microsoft TechNet: New-ADUser
- ↑ Microsoft TechNet: Get-ADUser
- ↑ Microsoft TechNet: Set-ADUser
- ↑ Microsoft TechNet: Remove-ADUser
- ↑ Microsoft TechNet: New-ADGroup
- ↑ Microsoft TechNet: Remove-ADGroup
- ↑ Microsoft TechNet: Add-ADGroupMember
- ↑ Microsoft TechNet: Remove-ADGroupMember
- ↑ Wikipedia: Object (computer science)
- ↑ Wikipedia: Hypertext Transfer Protocol
- ↑ Wikipedia: Hypertext Transfer Protocol
- ↑ Wikipedia: Simple Mail Transfer Protocol
- ↑ Wikipedia: Simple Mail Transfer Protocol
- ↑ Wikipedia: Simple Mail Transfer Protocol
- ↑ Wikipedia: Active Directory
- ↑ Wikipedia: Active Directory
- ↑ Wikipedia: Active Directory
- ↑ Microsoft TechNet: New-Object
- ↑ WindowsITPro: PowerShell Basics: Custom Objects
- ↑ Learn PowerShell: PowerShell and Excel
- ↑ Microsoft TechNet: Invoke-WebRequest
- ↑ Microsoft TechNet: Send-MailMessage
- ↑ Microsoft TechNet: Import-Module
- ↑ Microsoft TechNet: New-ADUser
- ↑ Microsoft TechNet: Get-ADUser
- ↑ Microsoft TechNet: Set-ADUser
- ↑ Microsoft TechNet: Remove-ADUser
- ↑ Microsoft TechNet: New-ADGroup
- ↑ Microsoft TechNet: Remove-ADGroup
- ↑ Microsoft TechNet: Add-ADGroupMember
- ↑ Microsoft TechNet: Remove-ADGroupMember
- ↑ Wikipedia: Component Object Model
- ↑ Wikipedia: HTML
- ↑ Wikipedia: Post Office Protocol
- ↑ Wikipedia: Internet Message Access Protocol