100% found this document useful (2 votes)
134 views

Get PowerShell Cookbook, 4th Edition Lee Holmes free all chapters

PowerShell

Uploaded by

weddigsimau
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
134 views

Get PowerShell Cookbook, 4th Edition Lee Holmes free all chapters

PowerShell

Uploaded by

weddigsimau
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Download the full version of the textbook now at textbookfull.

com

PowerShell Cookbook, 4th Edition Lee Holmes

https://textbookfull.com/product/powershell-
cookbook-4th-edition-lee-holmes/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

PowerShell Pocket Reference 3rd Edition Lee Holmes

https://textbookfull.com/product/powershell-pocket-reference-3rd-
edition-lee-holmes/

textbookfull.com

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/

textbookfull.com

Endless summer cookbook First Edition Katie Lee

https://textbookfull.com/product/endless-summer-cookbook-first-
edition-katie-lee/

textbookfull.com

Dialogues on the Theory and Practice of Literary


Translation 1st Edition Xu Jun

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

Advances in Body Area Networks I Post Conference


Proceedings of BodyNets 2017 Giancarlo Fortino

https://textbookfull.com/product/advances-in-body-area-networks-i-
post-conference-proceedings-of-bodynets-2017-giancarlo-fortino/

textbookfull.com

Methods in Statistical Mechanics A Modern View Osvaldo


Civitarese

https://textbookfull.com/product/methods-in-statistical-mechanics-a-
modern-view-osvaldo-civitarese/

textbookfull.com

Healing the Wounds of Gukurahundi in Zimbabwe A


Participatory Action Research Project 1st Edition Dumisani
Ngwenya
https://textbookfull.com/product/healing-the-wounds-of-gukurahundi-in-
zimbabwe-a-participatory-action-research-project-1st-edition-dumisani-
ngwenya/
textbookfull.com

Urban Planning and the Housing Market: International


Perspectives for Policy and Practice 1st Edition Nicole
Gurran
https://textbookfull.com/product/urban-planning-and-the-housing-
market-international-perspectives-for-policy-and-practice-1st-edition-
nicole-gurran/
textbookfull.com
Birds Of Prey Hawks Eagles Falcons and Vultures of North
America 1st Edition Pete Dunne

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

A NOTE FOR EARLY RELEASE READERS


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.
This will be the 1st chapter of the final book. Please note that the GitHub repo
will be made active later on.
f you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please visit https://www.powershellcookbook.com/4th_ed_techreview. You
can also reach out to the author at [email protected].

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:

brew install --cask powershell

Linux
Installation instructions vary per Linux distribution, but the most
common distribution among PowerShell Core users is Ubuntu:

# Update the list of packages


sudo apt-get update

# Install pre-requisite packages.


sudo apt-get install -y wget apt-transport-https software-
properties-common

# Download the Microsoft repository GPG keys


wget -q
https://packages.microsoft.com/config/ubuntu/20.04/packages
-microsoft-prod.deb

# Register the Microsoft repository GPG keys


sudo dpkg -i packages-microsoft-prod.deb

# Update the list of packages after we added


packages.microsoft.com
sudo apt-get update

# 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.

While you’re installing PowerShell from the Windows Store, now is a


good time to install the Windows Terminal application from the
Windows Store. The traditional console interface (the window that
PowerShell runs inside of) included in Windows has so many tools
and applications depending on its exact quirks that it is nearly
impossible to meaningfully change. It has fallen woefully behind on
what you would expect of a terminal console interface, so the
Windows Terminal application from the Windows Store is the
solution. Like PowerShell — it is open source, a focus of rapid
innovation, and a vast improvement to what ships in Windows by
default.
Figure 1-1. Windows Terminal running PowerShell, Bash, and even Azure Cloud
Shell!

You can run many shells within tabs in Windows Terminal:


PowerShell, Windows PowerShell, cmd.exe, Bash (if you’ve enabled
the Windows Subsystem for Linux), and even a connection to Azure
Cloud Shell. Windows Terminal defaults to PowerShell if you have it
installed.

Customizing PowerShell on Windows Terminal


There are two changes to a default Windows Terminal + PowerShell
installation that really improve the experience: taskbar pinning, and
themes.
Taskbar pinning
When you launch Windows Terminal, right-click on its taskbar icon.
Select “Pin to Taskbar”, and then drag the icon to the far left of the
taskbar. From now on, whenever you press the Windows Key + 1 at
the same time, you will either launch Windows Terminal and
PowerShell (if it’s not already open), or activate it. This is an
incredible way to keep your favorite shell close at hand.
Themes
Windows Powershell has a gorgeous Noble Blue theme. It is easy on
the eyes, quick to identify, and sets it apart from the dozens of other
shells out there. PowerShell Core did not take this color scheme with
it by default, but it is still possible to customize your installation.
From Windows Terminal, press Ctrl+Comma or click the downward
arrow on the right-hand side of the tab strip to open the Settings
dialog of Windows Terminal. The file that contains these settings will
open in your default text editor. Under Profiles, find the item with
Windows.Terminal.PowershellCore as its source, and add
Campbell PowerShell as a colorScheme. The result should
look like this:

{
"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.

1.2 Run Programs, Scripts, and Existing Tools

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

To run a command that contains a space in its name, enclose its


filename in single-quotes (') and precede the command with an
ampersand (&), known in PowerShell as the invoke operator:

& 'C:\Program Files\Program\Program.exe' arguments

To run a command in the current directory, place .\ in front of its


filename:

.\Program.exe arguments

To run a command with spaces in its name from the current


directory, precede it with both an ampersand and .\:

& '.\Program With Spaces.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.

Specifying the command name


The final three tips in the Solution merit special attention. They are
the features of PowerShell that many new users stumble on when it
comes to running programs. The first is running commands that
contain spaces. In cmd.exe, the way to run a command that
contains spaces is to surround it with quotes:

"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 >

So, a program name in quotes is no different from any other string


in quotes. It’s just an expression. As shown previously, the way to
run a command in a string is to precede that string with the invoke
operator (&). If the command you want to run is a batch file that
modifies its environment, see Recipe 3.5.

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.

Specifying command arguments


To specify arguments to a command, you can again type them just
as you would in other shells. For example, to make a specified file
read-only (two arguments to attrib.exe), simply type:

attrib +R c:\path\to\file.txt

Where many scripters get misled when it comes to command


arguments is how to change them within your scripts. For example,
how do you get the filename from a PowerShell variable? The
answer is to define a variable to hold the argument value, and just
use that in the place you used to write the command argument:
$filename = "c:\path\to\other\file.txt"
attrib +R $filename

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

If you see a solution that uses the Invoke-Expression cmdlet to


compose command arguments, it is almost certainly incorrect. The
Invoke-Expression cmdlet takes the string that you give it and
treats it like a full PowerShell script. As just one example of the
problems this can cause, consider the following: filenames are
allowed to contain the semicolon (;) character, but when Invoke-
Expression sees a semicolon, it assumes that it is a new line of
PowerShell script. For example, try running this:

$filename = "c:\file.txt; Write-Warning 'This could be


bad'"
Invoke-Expression "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

1.3 Run a PowerShell Command

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

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id


ProcessName
------- ------ ----- ----- ----- ------ -- ---
--------
133 5 11760 7668 46 1112
audiodg
184 5 33248 508 93 1692
avgamsvr
143 7 31852 984 97 1788
avgemc

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

1.4 Resolve Errors Calling Native Executables

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.

PS > cmd /c echo '!"#$%&''()*+,-./09:;<=>?@AZ[\]^_`az{|}~'


!"#$%&'()*+,-./09:;<=>?@AZ[\]^_`az{|}~

For complicated commands where this does not work, use the
verbatim argument (--%) syntax.

PS > cmd /c echo 'quotes' "and" $variables @{ etc = $true }


quotes and System.Collections.Hashtable

PS > cmd --% /c echo 'quotes' "and" $variables @{ etc =


$true }
'quotes' "and" $variables @{ etc = $true }

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.

Table 1-1. Sample of special characters


Special character Meaning

" The beginning (or end) of quoted text


Special character Meaning

# The beginning of a comment

$ The beginning of a variable

& Reserved for future use

( ) Parentheses used for subexpressions

; Statement separator

{ } Script block

| Pipeline separator

` Escape character

When surrounded by single quotes, PowerShell accepts these


characters as written, without the special meaning.
Despite these precautions, you may still sometimes run into a
command that doesn’t seem to work when called from PowerShell.
For the most part, these can be resolved by reviewing what
PowerShell passes to the command and escaping the special
characters.
To see exactly what PowerShell passes to that command, you can
view the output of the trace source called
NativeCommandParameterBinder:

PS > Trace-Command NativeCommandParameterBinder {


cmd /c echo '!"#$%&''()*+,-./09:;<=>?@AZ[\]^_`az{|}~'
} -PsHost

DEBUG: NativeCommandParameterBinder Information: 0 :


WriteLine
Argument 0: /c
DEBUG: NativeCommandParameterBinder Information: 0 :
WriteLine
Argument 1: echo
DEBUG: NativeCommandParameterBinder Information: 0 :
WriteLine
Argument 2: !#$%&'()*+,-./09:;<=>?@AZ[\]^_`az{|}~
!"#$%&'()*+,-./09:;<=>?@AZ[\]^_`az{|}~

If the command arguments shown in this output don’t match the


arguments you expect, they have special meaning to PowerShell and
should be escaped.
For a complex enough command that “just used to work,” though,
escaping special characters is tiresome. To escape the whole
command invocation, use the verbatim argument marker (--%) to
prevent PowerShell from interpreting any of the remaining
characters on the line. You can place this marker anywhere in the
command’s arguments, letting you benefit from PowerShell
constructs where appropriate. The following example uses a
PowerShell variable for some of the command arguments, but then
uses verbatim arguments for the rest:

PS > $username = "Lee"


PS > cmd /c echo Hello $username with 'quotes' "and"
$variables @{ etc = $true }
Hello Lee with quotes and System.Collections.Hashtable
PS > cmd /c echo Hello $username `
--% with 'quotes' "and" $variables @{ etc = $true }
Hello Lee with 'quotes' "and" $variables @{ etc = $true }

While in this mode, PowerShell also accepts cmd.exe-style


environment variables—as these are frequently used in commands
that “just used to work”:

PS > $env:host = "myhost"


PS > ping %host%
Ping request could not find host %host%. Please check the
name and try again.
PS > ping --% %host%
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Pinging myhost [127.0.1.1] with 32 bytes of data:
(...)

See Also
Appendix A

1.5 Supply Default Values for Parameters

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

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id


ProcessName
------- ------ ----- ----- ----- ------ -- -
----------
150 13 9692 9612 39 21.43 996
audiodg
1013 84 45572 42716 315 1.67 4596
WWAHost
(...)

PS > $PSDefaultParameterValues["Get-Process:ID"] = $pid


PS > Get-Process

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id


ProcessName
------- ------ ----- ----- ----- ------ -- -
----------
584 62 132776 157940 985 13.15 9104
powershell_ise
PS > Get-Process -Id 0

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id


ProcessName
------- ------ ----- ----- ----- ------ -- -
----------
0 0 0 20 0 0
Idle

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)

"Connecting as " + $Credential.UserName


}

Now, you can define a credential map:

PS > $credmap = @{}


PS > $credmap["RemoteComputer1"] = Get-Credential
PS > $credmap["RemoteComputer2"] = Get-Credential

Then, create a parameter default for all Credential parameters


that looks at the ComputerName bound parameter:

$PSDefaultParameterValues["*:Credential"] = {
if($args[0].BoundParameters -contains "ComputerName")
{
$cred =
$credmap[$PSBoundParameters["ComputerName"]]
if($cred) { $cred }
}
}

Here is an example of this in use:

PS > RemoteConnector -ComputerName RemoteComputer1


Connecting as UserForRemoteComputer1
PS > RemoteConnector -ComputerName RemoteComputer2
Connecting as UserForRemoteComputer2
PS > RemoteConnector -ComputerName RemoteComputer3

cmdlet RemoteConnector at command pipeline position 1


Supply values for the following parameters:
Credential: (...)

For more information about working with hashtables in PowerShell,


see Appendix A.

See Also
Appendix A

1.6 Invoke a Long-Running or Background


Command

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

Id Name State HasMoreData


Location
-- ---- ----- -----------
--------
1 Sleeper Running True
localhost

PS > Receive-Job Sleeper


671032665
1862308704
PS > Stop-Job Sleeper

Or, if your command is a single pipeline, place a & character at the


end of the line to run that pipeline in the background:

PS > dir c:\windows\system32 -recurse &

Id Name PSJobTypeName State


HasMore
Data
-- ---- ------------- ----- ------
-
1 Job1 BackgroundJob Running True

PS > 1+1
2

PS > Receive-Job -id 1 | Select -First 5

Directory: C:\Windows\System32

Mode LastWriteTime Length Name


---- ------------- ------ ----
d---- 12/7/2019 1:50 AM 0409
d---- 11/5/2020 7:09 AM 1028
d---- 11/5/2020 7:09 AM 1029
d---- 11/5/2020 7:09 AM 1031
d---- 11/5/2020 7:09 AM 1033
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XI.
Castlereagh’s long note of April 10, communicated by Foster to
the American government, contained a paragraph defining the British
doctrine of retaliation:—
“What Great Britain always avowed was her readiness to rescind
her orders as soon as France rescinded, absolutely and
unconditionally, her decrees. She never engaged to repeal those
orders as affecting America alone, leaving them in force against other
States, upon condition that France would except, singly and
especially, America from the operation of her decrees. She could not
do so without the grossest injustice to her allies, as well as all other
neutral nations; much less could she do so upon the supposition that
the special exception in favor of America was to be expressly granted
by France, as it has been hitherto tacitly accepted by America, upon
conditions utterly subversive of the most important and indisputable
maritime rights of the British empire.”

Long afterward Madison objected[172] to the common accounts of


the war, that they brought too little into view “the more immediate
impulse to it” given by this formal notice communicated to him
officially by Foster, which left no choice between war and
degradation. He regarded this notice as making further discussion
impossible. His idea was perhaps too strongly asserted, for Foster
offered, under other instructions, a new and important concession,—
that England should give up altogether her system of licensing trade
with the Continent, and in its place should enforce a rigorous
blockade;[173] but Madison and Monroe declined listening to any
offer that did not admit in principle the right of the United States to
trade with every European country.[174] Thus at the last moment the
dispute seemed to narrow itself to the single point of belligerent right
to blockade a coast.
Acting at once on the theory that Castlereagh’s instructions of
April 10 gave the last formal notice intended by the British
government, President Madison prepared a Message recommending
an immediate declaration of war. This Message was sent to
Congress June 1; the two Houses instantly went into secret session,
and the Message was read. No one could dispute the force of
Madison’s long recital of British outrages. For five years, the task of
finding excuses for peace had been more difficult than that of
proving a casus belli; but some interest still attached to the
arrangement and relative weight of the many American complaints.
Madison, inverting the order of complaints previously alleged,
began by charging that British cruisers had been “in the continued
practice of violating the American flag on the great highway of
nations, and of seizing and carrying off persons sailing under it.” The
charge was amply proved, was not denied, and warranted war; but
this was the first time that the Government had alleged impressment
as its chief grievance, or had announced, either to England or to
America, the intention to fight for redress,—and England might fairly
complain that she had received no notice of intended war on such
ground. The second complaint alleged that British cruisers also
violated the peace of the coasts, and harassed entering and
departing commerce. This charge was equally true and equally
warranted war, but it was open to the same comment as that made
upon the first. The third grievance on which the President had
hitherto founded his coercive measures consisted in “pretended
blockades, without the presence of an adequate force and
sometimes without the practicability of applying one,” by means of
which American commerce had been plundered on every sea,—a
practice which had come to its highest possible development in the
fourth grievance, the sweeping system of blockades known as the
Orders in Council. These four main heads of complaint covered
numbers of irritating consequences, but no other separate charge
was alleged, beyond an insinuation that the hostile spirit of the
Indians was connected with their neighborhood to Canada.
On the four great grievances thus defined every American could
in theory agree; but these admitted wrongs had hitherto been
endured as a matter of expediency, rather than resort to war; and the
opposition still stood on the ground that had been so obstinately held
by Jefferson,—that war, however just, was inexpedient. If union in
the war policy was to be hoped, the President must rather prove its
expediency than its justice. Even from his own point of view, two
doubts of expediency required fresh attention. For the first time,
England showed distinct signs of giving way; while on the other hand
France showed only the monomania of insisting on her decrees,
even to the point of conquering Russia. In the face of two such
movements, the expediency of war with England became more than
ever doubtful; and if the President wished for harmony, he must
remove these doubts. This he did not attempt, further than by
alluding to the sense of Castlereagh’s late despatch, as yet not in his
possession. What was still more remarkable, he said nothing in
regard to the contract with France, which since November, 1809, he
had made the ground for every measure of compulsion against
England. Indeed, not only was the contract ignored, but if any
meaning could be placed on his allusions to France, the theory of
contract seemed at last to be formally abandoned.
“Having presented this view of the relations of the United States
with Great Britain, and of the solemn alternative growing out of them, I
proceed to remark that the communications last made to Congress on
the subject of our relations with France will have shown that since the
revocation of her decrees, as they violated the neutral rights of the
United States, her government has authorized illegal captures by its
privateers and public ships; and that other outrages have been
practised on our vessels and our citizens. It will have been seen, also,
that no indemnity had been provided, or satisfactorily pledged, for the
extensive spoliations committed under the violent and retrospective
orders of the French government against the property of our citizens,
seized within the jurisdiction of France. I abstain at this time from
recommending to the consideration of Congress definite measures
with respect to that nation.”
The war of 1812 was chiefly remarkable for the vehemence with
which, from beginning to end, it was resisted and thwarted by a very
large number of citizens who were commonly considered, and who
considered themselves, by no means the least respectable,
intelligent, or patriotic part of the nation. That the war was as just and
necessary as any war ever waged, seemed so evident to Americans
of another generation that only with an effort could modern readers
grasp the reasons for the bitter opposition of large and respectable
communities which left the government bankrupt, and nearly severed
the Union; but if students of national history can bear with patience
the labor of retaining in mind the threads of negotiation which
President Madison so thoroughly tangled before breaking, they can
partially enter into the feelings of citizens who held themselves aloof
from Madison’s war. In June, 1812, the reasons for declaring war on
Great Britain, though strong enough, were weaker than they had
been in June, 1808, or in January, 1809. In the interval the British
government had laid aside the arrogant and defiant tones of
Canning’s diplomacy; had greatly modified the Orders in Council;
had offered further modifications; and had atoned for the
“Chesapeake” outrage. In 1807 England would have welcomed a
war with the United States; in 1812 she wanted peace, and yielded
much to secure it. In 1808 America was almost unanimous, her
government still efficient, well supplied with money, and little likely to
suffer from war; in 1812 the people were greatly divided, the
government had been weakened, and the Treasury was empty. Even
Gallatin, who in 1809 had been most decided for war, was believed
in 1812 to wish and to think that it might be avoided. Probably four
fifths of the American people held the same opinion. Not merely had
the situation in every other respect changed for the worse, but the
moral convictions of the country were outraged by the assertion of a
contract with Napoleon—in which no one believed—as the reason
for forcing religious and peaceful citizens into what they regarded as
the service of France.
The war Message of June 1 rather strengthened than removed
grounds of opposition. The President alleged but one reason for
thinking war expedient at that moment rather than at another; but
when in after years he insisted that Castlereagh’s instructions were
the immediate cause which precluded further negotiation, he
admitted his own mistake, and presumed that had Congress known
what was then passing in England the declaration of war would have
been suspended and negotiations renewed.[175] Such a succession
of mistakes, admitted one after another almost as soon as they were
made, might well give to Madison’s conduct the air so often
attributed to it, of systematic favor to Napoleon and equally
systematic hostility to England.
The House went at once into secret session; the Message was
referred to the Committee of Foreign Relations; and two days
afterward, June 3, Calhoun brought in a report recommending an
immediate appeal to arms. As a history of the causes which led to
this result, Calhoun’s report was admirable, and its clearness of style
and statement forced comparisons not flattering to the President’s
Message; but as an argument for the immediate necessity of war,
the report like the Message contented itself with bare assertions.
“The United States must support their character and station among
the nations of the earth, or submit to the most shameful
degradation.” Calhoun’s arguments were commonly close in logic,
and avoided declamation; but in the actual instance neither he nor
his followers seemed confident in the strength of their reasoning.
After the House had listened in secret session, June 3, to the
reading of this report, Josiah Quincy moved that the debate should
be public. The demand seemed reasonable. That preliminary
debates should be secret might be proper, but that war with any
Power, and most of all with England, should be declared in secret
could not be sound policy, while apart from any question of policy the
secrecy contradicted the professions of the party in power. Perhaps
no single act, in a hundred years of American history, showed less
regard for personal and party consistency than the refusal by the
Republicans of 1812 to allow society either rights or privileges in
regard to the declaration of war upon England. Quite apart from
military advantages to be hoped from secrecy, Henry Clay and his
friends were weary of debate and afraid of defeat. Only a few days
before, May 29, Clay forced Randolph from the floor by tactics which
showed that no more discussion was to be allowed. The secret
session gave the Speaker absolute power, and annihilated
opposition. By seventy-six votes to forty-six, the House rejected
Quincy’s motion; and a similar motion by Randolph shared the same
fate.
This demand being refused, the minority declined further
discussion. They said that any act of theirs which admitted the
validity of what they held to be a flagrant abuse of power could do no
good, and might create a dangerous precedent. Henceforward they
contented themselves with voting. On the same day Calhoun
presented the bill declaring war against England, and on the second
reading the opposition swelled to forty-five votes; while of the
Republican majority, numbering about one hundred and five
members, only seventy-six could be brought to the test. June 4 the
third reading was carried by a vote of seventy-eight to forty-five, and
the same day the bill passed by a vote of seventy-nine to forty-nine.
Proverbially wars are popular at their beginning; commonly, in
representative governments, they are declared by aid of some part
of the opposition. In the case of the War of 1812 the party in power,
instead of gaining strength by the declaration, lost about one fourth
of its votes, and the opposition actually gained nearly one fifth of the
Administration’s strength. In the Senate the loss was still greater.
There too the President’s Message was debated in secret, but the
proceedings were very deliberate. A select committee, with Senator
Anderson of Tennessee at its head, took charge of the Message, and
consumed a week in studying it. June 8 the committee reported the
House bill with amendments. June 11 the Senate, by a vote of
seventeen to thirteen, returned the bill to the committee for further
amendment. June 12 the committee reported the amendments as
instructed. The Senate discussed them, was equally divided, and
accordingly threw out its own amendments. June 15 the Senate
voted the third reading of the House bill by a vote of nineteen to
thirteen. June 16, after a strong speech for delay from Senator
James A. Bayard, the Senate again adjourned without action; and
only June 18, after two weeks of secret discussion, did the bill pass.
Nineteen senators voted in its favor; thirteen in opposition. Samuel
Smith, Giles, and Leib, the three Republican senators most openly
hostile to Madison, voted with the majority. Except Pennsylvania, the
entire representation of no Northern State declared itself for the war;
except Kentucky, every State south of the Potomac and the Ohio
voted for the declaration. Not only was the war to be a party
measure, but it was also sectional; while the Republican majority,
formerly so large, was reduced to dependence on the factious
support of Smith, Giles, and Leib.
The bill with its amendments was at once returned to the House
and passed. Without a moment’s delay the President signed it, and
the same day, June 18, 1812, the war began.
“The President’s proclamation was issued yesterday,” wrote
Richard Rush, the comptroller, to his father, June 20;[176] ... “he
visited in person—a thing never known before—all the offices of the
departments of war and the navy, stimulating everything in a manner
worthy of a little commander-in-chief, with his little round hat and huge
cockade.”
In resorting to old-fashioned methods of violence, Congress had
also to decide whether to retain or to throw away its weapons of
peaceful coercion. The Non-importation Act stopped importations
from England. If war should be considered as taking the place of
non-importation, it would have the curious result of restoring trade
with England. Opinions were almost as hotly divided on the question
of war with, or war without, non-importation as on the question of war
and peace itself; while even this detail of policy was distorted by the
too familiar interference of Napoleon,—for the non-importation was a
part of his system, and its retention implied alliance with him, while
the admission of English merchandise would be considered by him
almost an act of war. The non-importation was known to press
severely on the industries of England, but it threatened to paralyze
America. In the absence of taxation, nothing but the admission of
British goods into the United States could so increase the receipts of
the Treasury as to supply the government with its necessary
resources. Thus, two paths lay open. Congress might admit British
goods, and by doing so dispense with internal taxes, relieve the
commercial States, and offend France; or might shut out British
goods, disgust the commercial States, double the burden of the war
to America, but distress England and please Napoleon.
War having been declared June 18, on June 19 Langdon Cheves
introduced, from the Committee of Ways and Means, a bill partially
suspending the Non-importation Act. He supported his motion by a
letter from Gallatin, accepting this bill as an alternative to the tax
bills. On the same day news arrived of more American vessels
burned by French frigates. Chaos seemed beyond control. War with
England was about to restore commerce with her; alliance with
France was a state of war with her. The war party proposed to
depend on peace taxes at the cost of France their ally, in the
interests of England their enemy; the peace party called for war
taxes to discredit the war; both parties wanted trade with England
with whom they were at war; while every one was displeased with
the necessity of assisting France, the only ally that America
possessed in the world. Serurier went to the Secretary of State to
discuss this extraordinary situation, but found Monroe in no happy
temper.[177]
“He began by complaining to me of what, for that matter, I knew
already,—that a considerable number of new American ships, going to
Spain and Portugal and returning, had been very recently burned by
our frigates, and that others had been destroyed on the voyage even
to England. The Secretary of State on this occasion, and with
bitterness, renewed to me his complaints and those of the
Government and of Congress, whose discontent he represented as
having reached its height. I am, Monseigneur, as weary of hearing
these eternal grumblings as of having to trouble you with them; but I
think myself obliged to transmit to you whatever is said of an official
character. Mr. Monroe averred that for his part, as Secretary of State,
since he had never ceased down to this moment to maintain the
repeal of our decrees, he found himself suddenly compromised in the
face of his friends and of the public, and he must admit he had almost
lost the hope of an arrangement with us. Such were, Monseigneur, his
expressions; after which he retraced to me the system that the
Administration had never ceased pursuing with constancy and
firmness for eighteen months, and the last act of which had at length
been what I had seen, a formal declaration of war against England by
the republic,—‘at a moment,’ he added, ‘when it feels ill-assured of
France, and is so ill-treated by her.’ He finished at last by saying to
me, with a sort of political coquetry, that he was among his friends
obliged to admit that they had been too weak toward France, and that
perhaps they had been too quick in regard to England.”
Serurier wrote that the bitterness against France was really such
as would have caused a declaration of war against her as well as
against England, if the Administration had not stopped the
movement in Congress; nothing prevented the double war except
the military difficulties in its way. At the moment when, June 23, the
French minister was writing in these terms to the Duc de Bassano,
the House of Representatives was considering the action he feared.
Cheves had proposed to modify the non-importation,—the
Federalists moved to repeal it altogether; and although they were
defeated that day in committee, when Cheves’s bill came before the
House no less a champion than Calhoun rose to advocate the
reopening of trade.
Whatever Calhoun in those days did, was boldly and well done;
but his speech of June 24, 1812, against commercial restrictions,
was perhaps the boldest and the best of his early efforts. Neither
great courage nor much intelligence was needed to support war,
from the moment war became a party measure; but an attack on the
system of commercial restriction was a blow at Madison, which
belittled Jefferson, and threw something like contempt on the
Republican party from its beginning twenty years before, down to the
actual moment. How gently Calhoun did this, and yet how firmly he
laid his hands on the rein that was to guide his party into an opposite
path, could be seen in his short speech.
“The restrictive system, as a mode of resistance,” he said, “and a
means of obtaining a redress of our wrongs, has never been a favorite
one with me. I wish not to censure the motives which dictated it, or to
attribute weakness to those who first resorted to it for a restoration of
our rights.... I object to the restrictive system, and for the following
reasons,—because it does not suit the genius of our people, or that of
our government, or the geographical character of our country.”
With a single gesture, this young statesman of the new school
swept away the statesmanship of Jefferson and Madison, and waved
aside the strongest convictions of his party; but he did it with such
temperate statement, and with so serious a manner, that although he
said in effect little less than had been said for years by Federalists
and enemies, he seemed rather to lead than to oppose. “We have
had a peace like a war: in the name of heaven let us not have the
only thing that is worse,—a war like a peace.” That his voice should
be at once obeyed was not to be expected; but so many Republican
members followed Calhoun, Cheves, and Lowndes, that the
Federalists came within three votes of carrying their point; and so
equally divided was the House that, June 25, when the Federalists
returned to the attack and asked for a committee to report a bill
repealing the non-importation, the House divided sixty against sixty,
and the Speaker’s vote alone defeated the motion.
Greatly to the French minister’s relief the storm passed over; but
the heroic decision of Congress not only to punish England, but to
punish itself by deprivation of everything English,—not only to fight
Napoleon’s battles, but also to fight them under every disadvantage
that Napoleon chose to exact,—could not but increase the
vehemence of Northern hatred against the war, as it was certain to
increase Southern hatred against taxes. Gallatin knew not what to
expect. June 26 he wrote to a friend,[178]—
“We have not money enough to last till January 1 next, and
General Smith is using every endeavor to run us aground by opposing
everything,—treasury notes, double duties, etc. The Senate is so
nearly divided, and the division so increased by that on the war
question, that we can hardly rely on carrying anything.”
Although Gallatin caused the necessary bills for the war taxes to
be reported to the House June 26, he had no idea of passing them,
and was not surprised when by a vote of seventy-two to forty-six the
House postponed them to the next session, Calhoun and Cheves
voting with the Federalists against postponement. This chronic
helplessness could not last in face of war without stopping
government itself; and Congress, with a bad grace, yielded at last to
necessity. Even while Gallatin was complaining, the Senate passed
the bill for issuing five millions in treasury notes. June 30 it passed
the bill doubling the duties on imports. In rapid succession, such
other bills as were most needed by Government were put upon their
passage; and July 6 the exhausted Congress adjourned, glad to
escape its struggle with the novel problems of war.
In American history few sessions of Congress left a deeper mark
than that of 1811–12; but in the midst of the war excitement several
Acts of high importance almost escaped public notice. As far-
reaching as the declaration of war itself was the Act, approved April
8, 1812, declaring the State of Louisiana to be admitted into the
Union. Representatives of the Eastern States once more protested
against the admission of new territory without consulting the States
themselves; but Congress followed up the act by one more open to
question. West Florida had remained hitherto in the condition of its
military occupation a year before. Congress had then found the
problem too hard to solve on any theory of treaty or popular rights;
but in the excitement of the war fever Government acted on the new
principle that West Florida, which had been seized because it was a
part of Louisiana, should be treated as though it were a conquered
territory. An Act of Congress, approved April 14, divided the district in
halves at the Pearl River, and annexed the western half—against the
expressed wishes of its citizens[179]—to the new State of Louisiana;
the eastern portion was incorporated in the Mississippi Territory by
an Act approved May 14, 1812.
To the territory of West Florida the United States had no right.
Their ownership of the country between the Iberville and the Perdido
was a usurpation which no other country was bound to regard;
indeed, at the moment when Congress subjected the shores of
Mobile Bay to the Mississippi Territorial government, Mobile was still
garrisoned by a Spanish force and ruled by the Spanish people. The
case of West Florida was the more curious, because in after years
the United States government, in order to obtain a title good beyond
its own borders, accepted the territory as a formal grant from the
King of Spain. Ferdinand VII., the grantor and only rightful interpreter
of his own grant,[180] inserted an article into the treaty of 1819 which
was intended by him to discredit, and did in fact ignore, the
usurpations of the United States: “His Catholic Majesty cedes to the
United States, in full property and sovereignty, all the territories
which belong to him situated to the eastward of the Mississippi,
known by the names of East and West Florida.”[181] According to the
Acts of Congress, no territory known as West Florida belonged to the
King of Spain, but had been ceded to the United States as a part of
Louisiana. The admission by treaty in 1819 that Ferdinand VII. was
still sovereign over any territory known by the name of West Florida,
threw discredit on the previous acts of President and Congress, and
following the confusion due to the contradictory systems they had
pursued, created a chaos which neither proclamations, Acts of
Congress, treaties, nor decisions of the courts, numerous and
positive as they might be, could reduce to order. History cannot tell
by what single title the United States hold West Florida.
East Florida threatened to become a worse annoyance. In
January, 1811, as the story has told, the President, under authority of
a secret Act of Congress, sent George Matthews and John McKee to
take possession, under certain circumstances, of Mobile and
Fernandina. Their written instructions were singularly loose.[182] In
general they were to take possession of East Florida only in case the
Spanish authorities or “the existing local authority” should wish it, or
in case of actual British interference; but their conduct was to be
“regulated by the dictates of their own judgments, on a close view
and accurate knowledge of the precise state of things there, and of
the real disposition of the Spanish government.” Besides these
written instructions, Matthews professed to be guided by verbal
explanations of a stronger character. With the precedent of Baton
Rouge before his eyes, Matthews could not but assume that he was
sent to St. Mary’s for a practical object; and he found there a
condition of affairs that seemed to warrant him in acting with energy.
St. Mary’s River was filled with British vessels engaged in smuggling
British merchandise into the United States in defiance of the Non-
importation Act; while Amelia Island, on which the town of
Fernandina stood, was a smuggling depot, and the Spanish authority
an empty form, useful only for the protection of illicit trade.
Matthews’s official reports assumed as a matter of course an
intention in his Government to possess itself of East Florida. His
letters made no disguise of his own acts or intentions. After six
months of inquiry, he wrote to Secretary Monroe, Aug. 3, 1811, a
plain account of the measures necessary to be taken:[183]—
“I ascertained that the quiet possession of East Florida could not
be obtained by an amicable negotiation with the powers that exist
there; ... that the inhabitants of the province are ripe for revolt. They
are, however, incompetent to effect a thorough revolution without
external aid. If two hundred stand of arms and fifty horsemen’s swords
were in their possession, I am confident they would commence the
business, and with a fair prospect of success. These could be put into
their hands by consigning them to the commanding officer at this post,
subject to my order. I shall use the most discreet management to
prevent the United States being committed; and although I cannot
vouch for the event, I think there would be but little danger.”
In October, Matthews communicated freely his plans and wishes
to Senator Crawford, and commissioned him to explain them to the
Government.[184] The President was fully acquainted with them, and
during six months offered no objection, but waited in silence for
Matthews to effect the revolution thus prepared.
Matthews carried out his mission by following the West Florida
precedent as he understood it. March 16, 1812, some two hundred
self-styled insurgents crossed the river, landed on Amelia Island, and
summoned the garrison of Fernandina to surrender. At the same
time the American gunboats, stationed on the river, took a position to
watch the movement. The Spanish commandant sent to inquire
whether the American gunboats meant to assist the insurgents, and
receiving an answer in the affirmative, he capitulated to the so-called
patriots.[185] Independence was declared; an independent flag was
raised; and when this formality ended, the patriots summoned
General Matthews, who crossed the river with a company of the
regular army, and March 19 took possession of Amelia Island,
subject to the President’s approval.
Matthews supposed his measures to be warranted by his
instructions, and thought the Government bound to sustain him; but
the Government took an opposite course. April 4 Monroe wrote to
Matthews[186] disavowing the seizure of Amelia Island, and referring
to the precedent of Baton Rouge as the proper course to have
followed. “The United States did not take possession until after the
Spanish authority had been subverted by a revolutionary proceeding,
and the contingency of the country being thrown into foreign hands
had forced itself into view.” Matthews failed to see why one
“revolutionary proceeding” was not as good as another, or why the
fiction of foreign interference might not serve as well at Fernandina
as at Baton Rouge. He was excessively indignant, and believed his
disavowal to be due to the publication of John Henry’s letters, which
had made the President suddenly sensitive to the awkwardness of
doing openly acts which he imputed as a crime in the governor-
general of Canada to imagine. Senator Crawford afterward wrote to
Monroe[187] that this impression was by no means confined to
Matthews; indeed, Crawford himself seemed to share it. Yet
governments were not bound to make explanations to their
instruments; and Matthews was told only that he had mistaken the
President’s wishes, and that his instructions were meant in good
faith to require that the Spaniards should of their own accord ask to
surrender their territory to the United States.
April 24 Madison wrote to Jefferson:[188] “In East Florida
Matthews has been playing a strange comedy in the face of
common-sense as well as of his instructions. His extravagances
place us in the most distressing dilemma.” The dilemma consisted in
the President’s wish to maintain possession of Amelia Island, and
the difficulty of doing it. In explaining the matter to the French
minister, Monroe made no secret of the President’s wishes:[189]—
“Mr. Monroe, in communicating the facts to me at one of our last
conversations, told me that General Matthews had gone beyond his
orders; that he was told to observe only; and in case a third Power,
which could be only England, should present itself to occupy the
island, he was to prevent it if possible, and in case of necessity
repulse the disembarking troops. He added that nevertheless, now
that things had reached their present condition, there would be more
danger in retreating than in advancing; and so, while disavowing the
General’s too precipitate conduct, they would maintain the
occupation.”
This decision required some double dealing. April 10 Monroe
wrote[190] to the governor of Georgia, requesting him to take
Matthews’s place and to restore Amelia Island to the Spanish
authorities; but this order was for public use only, and not meant to
be carried into effect. May 27 Monroe wrote again,[191] saying:—
“In consequence of the compromitment of the United States to the
inhabitants, you have been already instructed not to withdraw the
troops unless you find that it may be done consistently with their
safety, and to report to the Government the result of your conferences
with the Spanish authorities, with your opinion of their views, holding
in the mean time the ground occupied.”
Governor Mitchell would have been a poor governor and still
poorer politician, had he not read such instructions as an order to
hold Amelia Island as long as possible. Instead of re-establishing the
Spanish authority at Fernandina, he maintained the occupation
effected by Matthews.[192] June 19, the day after declaring war
against England, the House took up the subject on the motion of
Troup of Georgia, and in secret session debated a bill authorizing
the President not to withdraw the troops, but to extend his
possession over the whole country of East and West Florida, and to
establish a government there.[193] June 25, by a vote of seventy to
forty-eight, the House passed this bill, which in due time went
successfully through all its stages in the Senate until July 3, when
the vote was taken on its passage. Only then three Northern
Republicans,—Bradley of Vermont, Howell of Rhode Island, and Leib
of Pennsylvania,—joining Giles, Samuel Smith, and the Federalists,
defeated, by a vote of sixteen to fourteen, this bill which all the
President’s friends in both Houses supported as an Administration
measure, and upon which the President promised to act with
decision; but even after its failure the President maintained
possession of Fernandina, with no other authority than the secret Act
of Congress which had been improperly made by Matthews the
ground of usurping possession.
From the pacific theories of 1801 to the military methods of 1812
was a vast stride. When Congress rose, July 6, 1812, the whole
national frontier and coast from Prairie du Chien to Eastport, from
Eastport to St. Mary’s, from St. Mary’s to New Orleans,—three
thousand miles, incapable of defence,—was open to the attacks of
powerful enemies; while the Government at Washington had taken
measures for the military occupation of the vast foreign territories
northward of the Lakes and southward to the Gulf of Mexico.
CHAPTER XII.
While the Twelfth Congress at Washington from November,
1811, until July, 1812, struggled with the declaration which was to
spread war westward to the Mississippi River, Napoleon at Paris
prepared the numberless details of the coming campaign that was to
ravage Europe eastward as far as Moscow; and in this fury for
destruction, no part remained for argument or diplomacy. Yet Joel
Barlow, full of hope that he should succeed in solving the problem
which had thus far baffled his Government, reached Paris, Sept. 19,
1811, and began a new experience, ended a year later at Zarnovitch
in Poland by a tragedy in keeping with the military campaign to which
Barlow was in a fashion attached.
Joel Barlow felt himself at home in Paris. In 1788, at the age of
thirty-four, he had first come abroad, and during seventeen exciting
years had been rather French than American. In 1792 the National
Convention conferred on him the privileges of French citizenship,—
an honor then shared only by Washington and Hamilton among
Americans. He felt himself to be best understood and appreciated by
Frenchmen. His return to France in 1812 was, he said, attended by a
reception much more cordial and friendly than that which he had
received in America, in 1805, on his return to his native country after
seventeen years of absence. He settled with delight into his old
society, even into his old house in the Rue Vaugirard, and relished
the pleasure of recovering, with the highest dignity of office, the
atmosphere of refinement which he always keenly enjoyed. Yet
when these associations lost their freshness, and he turned to his
diplomatic task, he found that few lots in life were harder than that of
the man who bound himself to the destinies of Napoleon.
On the success of Barlow’s mission the fate of President Madison
might depend. As long as France maintained her attitude of hostility
to the United States, war against England would be regarded by a
majority of the Northern people with distrust and dislike. On that
point Madison was justly timid. The opposition of New England and
New York must be quieted, and in order to quiet it Madison must
prove France to be honest in respecting American rights; he must
show that the decrees had been really repealed as he had so often
and still so obstinately asserted, and that the vast confiscations of
American property under the authority of those decrees would
receive indemnity. The public had commonly supposed France to be
comparatively a slight aggressor; but to the general surprise, when
Congress, before the declaration of war against England, called for a
return of captures under the belligerent edicts, Monroe’s report
showed that the seizures by France and by the countries under her
influence in pursuance of the decrees were not less numerous than
those made by England under the Orders in Council. The precise
values were never known. The confiscations ordered by Napoleon in
Spain, Naples, Holland, Denmark, Hamburg, and on the Baltic
outnumbered those made in his empire; but all these taken together
probably exceeded the actual condemnations in British prize-courts.
This result, hardly expected by the American government, added to
its embarrassment, but was only a part of its grievances against
Napoleon. Not only had France since 1807 surpassed England in
her outrages on American property, but while England encouraged
American commerce with her own possessions, Napoleon
systematically prohibited American commerce with his empire. He
forbade American vessels to import sugar or other colonial produce
except by special license; he imposed a duty of sixty cents a pound
on Georgia cotton worth twenty or twenty-five cents; he refused to
take tobacco except in small quantities as a part of the government
monopoly; and he obliged every American ship to carry for its return
cargo two thirds in silks and the other third in wines, liquors, and
such other articles of French produce as he might direct. The official
returns made to Congress showed that in 1811 the United States
exported domestic produce to the amount of $45,294,000, of which
France and Italy took only $1,164,275.
Barlow’s instructions required him to reform these evils, but they
especially insisted upon indemnity for seizures under the decrees.
Haste was required; for Congress could not be expected to adopt
extreme measures against England until France should have made
such concessions as would warrant the American government in
drawing a distinction between the two belligerents. Barlow arrived in
Paris September 19, only to learn that on the same day the Emperor
set out for Antwerp and Amsterdam. The Duc de Bassano received
him kindly, assured him of the Emperor’s order to begin upon
business at once, and listened courteously to the American
complaints and demands. Then he too departed for Holland, whence
he returned only November 9, when at Washington Congress had
been already a week in session.
Nothing showed this delay to be intentional; but Napoleon never
allowed delay when he meant to act, and in the present instance he
was not inclined to act. Although the Duc de Bassano made no reply
to Barlow, he found time at Amsterdam to write instructions to
Serurier.[194] In these he declared that all American vessels captured
since November, 1810, had been released, except those coming by
way of England, which were not yet condemned, but only
sequestered.
“The French government would like to know, before making a
decision, how England would act toward American ships bound for
France. If I return once more on the motives for this delay, it is only for
your personal instruction and without making it a subject of an official
declaration on your part. On this question you should speak as for
yourself; appear ignorant what are the true motives for still detaining
some American ships which have had communication with England;
restrict yourself to receiving the representations sent you, and to
declaring that you will render an account of them; in short, give no
explanation that would imply that the Decrees of Berlin and Milan are
not entirely revoked.”
While the Emperor was thus secretly determined to enforce his
decrees, he was equally determined to pay no indemnities. Against
sacrifices of money Napoleon always made unconquerable
resistance.
In due time Barlow had his audience of reception, and made to
the Emperor a speech, not without flattery. He ventured to mention
his commercial objects, in the hope of calling out an answer that
would suit his purpose. Napoleon’s reply proved for the hundredth
time the danger of risking such experiments:—
“As to the commerce between the two Powers, I desire to favor it. I
am great enough to be just. But on your part you must defend your
dignity against my enemies and those of the Continent. Have a flag,
and I will do for you all that you can desire.”
In reporting the interview to Monroe, Barlow added that the
ambiguity of the Emperor’s reply made it unfit for publication.[195]
Ambiguity was not the quality that a more sensitive man would have
ascribed to a rebuff so sharp; but whatever the President may have
thought, he took Barlow’s advice. The interview was never made
known to Congress.
During the month of November Napoleon busied himself in
commercial questions only in order to show liberality to England at
the expense of America. He extended his system of licenses to the
exchange of French wines for sugar in large quantities, and even to
the importation of coffee, indigo, tea, wool, dyewoods, and other
articles, all to be obtained from England by license.[196] He
discovered that his exchanges would benefit France more than
England in the proportion of three to one. “It is therefore the
perfected system that has produced this result, which had not been
expected for several years. Evidently the system thus established is
a permanent system, which can be made perpetual.”[197] The motive
for this discovery might be traced throughout all his economical
experiments. He needed money.
Never had Napoleon’s ministers a harder task to give his acts a
color of consistency. During the months of November and December
Barlow held many interviews with Bassano, and made earnest
efforts to obtain some written pledge in favor of American interests,
but without success. December 19 he wrote that he was almost
discouraged by the unexpected and unreasonable delay.[198]
Napoleon made no more seizures, and released such American
vessels as were held for violation of the decrees; but he conceded
nothing in principle, and was far from abandoning his fiscal system
against the United States. In order to meet Barlow’s complaints,
Bassano gathered together every token of evidence that the decrees
were not in force; but while he was asking the American minister
how these facts could be doubted, a French squadron, Jan. 8, 1812,

You might also like