Get PowerShell Cookbook, 4th Edition Lee Holmes free all chapters
Get PowerShell Cookbook, 4th Edition Lee Holmes free all chapters
com
https://textbookfull.com/product/powershell-
cookbook-4th-edition-lee-holmes/
https://textbookfull.com/product/powershell-pocket-reference-3rd-
edition-lee-holmes/
textbookfull.com
https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/
textbookfull.com
https://textbookfull.com/product/endless-summer-cookbook-first-
edition-katie-lee/
textbookfull.com
https://textbookfull.com/product/dialogues-on-the-theory-and-practice-
of-literary-translation-1st-edition-xu-jun/
textbookfull.com
Wolf War The Twilight of Humanity 1st Edition Morris
https://textbookfull.com/product/wolf-war-the-twilight-of-
humanity-1st-edition-morris/
textbookfull.com
https://textbookfull.com/product/advances-in-body-area-networks-i-
post-conference-proceedings-of-bodynets-2017-giancarlo-fortino/
textbookfull.com
https://textbookfull.com/product/methods-in-statistical-mechanics-a-
modern-view-osvaldo-civitarese/
textbookfull.com
https://textbookfull.com/product/birds-of-prey-hawks-eagles-falcons-
and-vultures-of-north-america-1st-edition-pete-dunne/
textbookfull.com
PowerShell Cookbook
FOURTH EDITION
Your Complete Guide to Scripting the Ubiquitous Object-Based Shell
With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
Lee Holmes
PowerShell Cookbook
by Lee Holmes
Copyright © 2021 O’Reilly Media. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles
(http://oreilly.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
[email protected].
Acquisitions Editor: Suzanne McQuade
Development Editor: Angela Rufino
Production Editor: Kate Galloway
Interior Designer: David Futato
Cover Designer: Karen Montgomery
Illustrator: Kate Dullea
June 2021: Fourth Edition
Revision History for the Early Release
2021-01-21: First Release
See http://oreilly.com/catalog/errata.csp?isbn=9781098101602 for
release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc.
PowerShell Cookbookem>, the cover image, and related trade dress
are trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the author, and do not
represent the publisher’s views. While the publisher and the author
have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and
the author disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting from
the use of or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any code
samples or other technology this work contains or describes is
subject to open source licenses or the intellectual property rights of
others, it is your responsibility to ensure that your use thereof
complies with such licenses and/or rights.
978-1-098-10154-1
Chapter 1. The PowerShell
Interactive Shell
1.0 Introduction
Above all else, the design of PowerShell places priority on its use as
an efficient and powerful interactive shell. Even its scripting
language plays a critical role in this effort, as it too heavily favors
interactive use.
What surprises most people when they first launch PowerShell is its
similarity to the command prompt that has long existed as part of
Windows. Familiar tools continue to run. Familiar commands
continue to run. Even familiar hotkeys are the same. Supporting this
familiar user interface, though, is a powerful engine that lets you
accomplish once cumbersome administrative and scripting tasks with
ease.
This chapter introduces PowerShell from the perspective of its
interactive shell.
1.1 Install PowerShell Core
Problem
You want to install the most recent version of PowerShell on your
Windows, Mac, or Linux system.
Solution
Visit https://microsoft.com/PowerShell to find the installation
instructions for the operating system and platform you want to
install on. For the most common:
Windows
Install PowerShell from Microsoft through the the Microsoft Store
application in the Start Menu. Then, install Windows Terminal from
Microsoft through the Microsoft Store application in the Start Menu.
Mac
Install PowerShell from Homebrew:
Linux
Installation instructions vary per Linux distribution, but the most
common distribution among PowerShell Core users is Ubuntu:
# Install PowerShell
sudo apt-get install -y powershell
Discussion
PowerShell has already led a long and exciting life. For the first
fifteen years of its existence, it was known as “Windows
PowerShell”: a fantastic object-based management shell and
platform that made it easy and fun for administrators, developers,
and power users to get their jobs done.
In its earliest stages, this support came as part of the “Windows
Management Framework”: a standalone download that provided this
much needed functionality on Windows. Windows PowerShell
eventually became part of Windows itself, and has been a core part
of the operating system since Windows 7.
In 2016, PowerShell made a tremendous shift by announcing that it
would ship PowerShell on multiple operating system platforms — and
by the way — open source the entire project at the same time!
Windows PowerShell got a new name with its new future: simply
PowerShell. This major change opened the doors for vastly quicker
innovation, community participation, and availability through
avenues that previously would never have been possible. While the
classic Windows PowerShell is still included in the operating system
by default, it no longer receives updates and should be avoided.
Installing and Running PowerShell on Windows
As mentioned in the Solution, the best way to get PowerShell is to
install it through the Windows Store. This makes it easy to install
and easy to update. Once you’ve installed it, you can find PowerShell
in the Start Menu like you would any other application.
NOTE
If you want to install a system-wide version of PowerShell for
automation and other adminstration tasks, you will likely prefer the MSI-
based installation mechanism. For more information, see
https://microsoft.com/PowerShell.
{
"guid": ...
"hidden": false,
"name": "PowerShell",
"colorScheme": "Campbell Powershell",
"source": "Windows.Terminal.PowershellCore"
},
Pay attention to quotes, colons, and commas, and you should have
your PowerShell sessions looking noble again in no time!
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Installing and Running PowerShell on Mac and Linux
For the most part, installing PowerShell on Mac and Linux follows the
patterns that you are likely already familiar with.
On Mac, the recommended installation method is through the
popular Homebrew package manager. Homebrew is not installed by
default on MacOS, but installation is quite easy. If you haven’t
installed Homebrew yet, you can find instructions at https://brew.sh.
On Linux, the installation methods vary depending on the
distribution you are interested in. For the most part, installation is as
simple as registering the Microsoft repository for your distribution’s
package manager, and then installing PowerShell. The Solution
provides an example specific to Ubuntu 20.04, but you can specific
instructions for your distribution and specific version here:
https://docs.microsoft.com/en-
us/powershell/scripting/install/installing-powershell-core-on-linux.
Problem
You rely on a lot of effort invested in your current tools. You have
traditional executables, Perl scripts, VBScript, and of course, a legacy
build system that has organically grown into a tangled mess of batch
files. You want to use PowerShell, but you don’t want to give up
everything you already have.
Solution
To run a program, script, batch file, or other executable command in
the system’s path, enter its filename. For these executable types, the
extension is optional:
Program.exe arguments
ScriptName.ps1 arguments
BatchFile.cmd arguments
.\Program.exe arguments
Discussion
In this case, the solution is mainly to use your current tools as you
always have. The only difference is that you run them in the
PowerShell interactive shell rather than cmd.exe.
"C:\Program Files\Program\Program.exe"
In PowerShell, though, placing text inside quotes is part of a feature
that lets you evaluate complex expressions at the prompt, as shown
in Example 1-1.
Example 1-1. Evaluating expressions at the PowerShell prompt
PS > 1 + 1
2
PS > 26 * 1.15
29.9
PS > "Hello" + " World"
Hello World
PS > "Hello World"
Hello World
PS > "C:\Program Files\Program\Program.exe"
C:\Program Files\Program\Program.exe
PS >
NOTE
By default, PowerShell’s security policies prevent scripts from running.
Once you begin writing or using scripts, though, you should configure
this policy to something less restrictive. For information on how to
configure your execution policy, see Recipe 18.1.
The second command that new users (and seasoned veterans before
coffee!) sometimes stumble on is running commands from the
current directory. In cmd.exe, the current directory is considered
part of the path: the list of directories that Windows searches to find
the program name you typed. If you are in the C:\Programs
directory, cmd.exe looks in C:\Programs (among other places) for
applications to run.
PowerShell, like most Unix shells, requires that you explicitly state
your desire to run a program from the current directory. To do that,
you use the .\Program.exe syntax, as shown previously. This
prevents malicious users on your system from littering your hard
drive with evil programs that have names similar to (or the same as)
commands you might run while visiting that directory.
To save themselves from having to type the location of commonly
used scripts and programs, many users put commonly used utilities
along with their PowerShell scripts in a “tools” directory, which they
add to their system’s path. If PowerShell can find a script or utility in
your system’s path, you do not need to explicitly specify its location.
If you want PowerShell to automatically look in your current working
directory for scripts, you can add a period (.) to your PATH
environment variable.
For more information about updating your system path, see Recipe
16.2.
If you want to capture the output of a command, you can either
save the results into a variable, or save the results into a file. To
save the results into a variable, see Recipe 3.3. To save the results
into a file, see Recipe 9.2.
attrib +R c:\path\to\file.txt
You can use the same technique when you call a PowerShell cmdlet,
script, or function:
$filename = "c:\path\to\other\file.txt"
Get-Acl -Path $filename
Given that these dynamic arguments often come from user input,
using Invoke-Expression to compose commands can (at best)
cause unpredictable script results. Worse, it could result in damage
to your system or a security vulnerability.
In addition to letting you supply arguments through variables one at
a time, PowerShell also lets you supply several of them at once
through a technique known as splatting. For more information about
splatting, see Recipe 11.14.
See Also
Recipe 3.3
Recipe 3.5
Recipe 11.14
Recipe 16.2
Recipe 18.1
Problem
You want to run a PowerShell command.
Solution
To run a PowerShell command, type its name at the command
prompt. For example:
PS > Get-Process
Discussion
The Get-Process command is an example of a native PowerShell
command, called a cmdlet. As compared to traditional commands,
cmdlets provide significant benefits to both administrators and
developers:
They share a common and regular command-line syntax.
They support rich pipeline scenarios (using the output of one
command as the input of another).
They produce easily manageable object-based output, rather than
error-prone plain-text output.
Because the Get-Process cmdlet generates rich object-based
output, you can use its output for many process-related tasks.
Every PowerShell command lets you provide input to the command
through its parameters. For more information on providing input to
commands, see Appendix A.
The Get-Process cmdlet is just one of the many that PowerShell
supports. See Recipe 1.12 to learn techniques for finding additional
commands that PowerShell supports.
For more information about working with classes from the .NET
Framework, see Recipe 3.8.
See Also
Recipe 1.12
Recipe 3.8
Appendix A
Problem
You have a command line that works from cmd.exe, and want to
resolve errors that occur from running that command in PowerShell.
Solution
Enclose any affected command arguments in single quotes to
prevent them from being interpreted by PowerShell, and replace any
single quotes in the command with two single quotes.
For complicated commands where this does not work, use the
verbatim argument (--%) syntax.
Discussion
One of PowerShell’s primary goals has always been command
consistency. Because of this, cmdlets are very regular in the way
that they accept parameters. Native executables write their own
parameter parsing, so you never know what to expect when working
with them. In addition, PowerShell offers many features that make
you more efficient at the command line: command substitution,
variable expansion, and more. Since many native executables were
written before PowerShell was developed, they may use special
characters that conflict with these features.
As an example, the command given in the Solution uses all the
special characters available on a typical keyboard. Without the
quotes, PowerShell treats some of them as language features, as
shown in Table 1-1.
; Statement separator
{ } Script block
| Pipeline separator
` Escape character
See Also
Appendix A
Problem
You want to define a default value for a parameter in a PowerShell
command.
Solution
Add an entry to the PSDefaultParameterValues hashtable.
PS > Get-Process
Discussion
In PowerShell, many commands (cmdlets and advanced functions)
have parameters that let you configure their behavior. For a full
description of how to provide input to commands, see Appendix A.
Sometimes, though, supplying values for those parameters at each
invocation becomes awkward or repetitive.
In early versions of PowerShell, it was the responsibility of each
cmdlet author to recognize awkward or repetitive configuration
properties and build support for “preference variables” into the
cmdlet itself. For example, the Send-MailMessage cmdlet looks
for the $PSEmailServer variable if you do not supply a value for
its -SmtpServer parameter.
To make this support more consistent and configurable, PowerShell
supports the PSDefaultParameterValues preference variable.
This preference variable is a hashtable. Like all other PowerShell
hashtables, entries come in two parts: the key and the value.
Keys in the PSDefaultParameterValues hashtable must match
the pattern cmdlet:parameter—that is, a cmdlet name and
parameter name, separated by a colon. Either (or both) may use
wildcards, and spaces between the command name, colon, and
parameter are ignored.
Values for the cmdlet/parameter pairs can be either a simple
parameter value (a string, boolean value, integer, etc.) or a script
block. Simple parameter values are what you will use most often.
If you need the default value to dynamically change based on what
parameter values are provided so far, you can use a script block as
the default. When you do so, PowerShell evaluates the script block
and uses its result as the default value. If your script block doesn’t
return a result, PowerShell doesn’t apply a default value.
When PowerShell invokes your script block, $args[0] contains
information about any parameters bound so far:
BoundDefaultParameters, BoundParameters, and
BoundPositionalParameters. As one example of this, consider
providing default values to the -Credential parameter based on
the computer being connected to. Here is a function that simply
outputs the credential being used:
function RemoteConnector
{
param(
[Parameter()]
$ComputerName,
[Parameter(Mandatory = $true)]
$Credential)
$PSDefaultParameterValues["*:Credential"] = {
if($args[0].BoundParameters -contains "ComputerName")
{
$cred =
$credmap[$PSBoundParameters["ComputerName"]]
if($cred) { $cred }
}
}
See Also
Appendix A
Problem
You want to invoke a long-running command on a local or remote
computer.
Solution
Invoke the command as a Job to have PowerShell run it in the
background:
PS > Start-Job { while($true) { Get-Random; Start-Sleep 5 }
} -Name Sleeper
PS > 1+1
2
Directory: C:\Windows\System32