41,99 €
Master the art of automating and managing your environment using PowerShell
If you are a system administrator who wants to become an expert in controlling and automating your Windows environment, then this book is for you. It is also for those new to the PowerShell language.
PowerShell scripts offer a handy way to automate various chores. Working with these scripts effectively can be a difficult task.
This comprehensive guide starts from scratch and covers advanced-level topics to make you a PowerShell expert. The first module, PowerShell Fundamentals, begins with new features, installing PowerShell on Linux, working with parameters and objects, and also how you can work with .NET classes from within PowerShell.
In the next module, you'll see how to efficiently manage large amounts of data and interact with other services using PowerShell. You'll be able to make the most of PowerShell's powerful automation feature, where you will have different methods to parse and manipulate data, regular expressions, and WMI.
After automation, you will enter the Extending PowerShell module, which covers topics such as asynchronous processing and, creating modules. The final step is to secure your PowerShell, so you will land in the last module, Securing and Debugging PowerShell, which covers PowerShell execution policies, error handling techniques, and testing.
By the end of the book, you will be an expert in using the PowerShell language.
This practical guide covers all the advanced PowerShell functionalities that an administrator needs to learn to automate their environments.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 397
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2015
Second edition: October 2017
Production reference: 1251017
ISBN 978-1-78712-630-5
www.packtpub.com
Authors
Chris Dent
Brenton J.W. Blawat
Project Coordinator
Kinjal Bari
Reviewer
Paul Broadwith
Proofreader
Safis Editing
Acquisition Editor
Meeta Rajani
Indexer
Tejal Daruwale Soni
Content Development Editor
Mamata Walkar
Graphics
Kirk D'penha
Technical Editor
Varsha Shivhare
Production Coordinator
Nilesh Mohite
Copy Editors
Safis Editing
Ulka Manjrekar
Chris Dent is a professional PowerShell developer based in and around London with over 8 years experience in that language alone. He is also proficient in C#, VBScript, Perl, and Python, but PowerShell is his favorite by a wide margin. He is also the author of dnshell.
He describes himself as being a toolset or module developer (he rarely writes scripts in the one-off sense); he has a deep interest in formalized development approaches, continuous integration, secure coding practices, and creating supportable automation frameworks within organizations.
Brenton J.W. Blawat is an entrepreneur, strategic technical advisor, author, and enterprise architect, who has a passion for the procurement of technology in profit-based organizations. He is business-centric and technology-minded. Brenton has many years of experience in bridging the gap between technical staff and decision-makers in several organizations. He takes pride in his ability to effectively communicate with a diverse audience and provide strategic direction for large and small organizations alike.
In 2013, Brenton authored his first book, PowerShell 3.0 WMI Starter, Packt Publishing. In March 2015, he authored his second book, Mastering Windows PowerShell Scripting, with Packt Publishing.
Brenton currently works at CDW as an Enterprise Architect in strategic solutions and services. CDW is a leading multibrand technology solutions provider in the fields of business, government, education, and healthcare. A Fortune 500 company, it was founded in 1984 and employs approximately 7,200 coworkers. In 2016, the company generated net sales of more than $13.0 billion.
His current specialization sits on top of 15 years of experience spread across (predominantly Microsoft) systems, (Juniper and Cisco) networking, and security.
Paul Broadwith is a senior technology professional freelancing in Scotland. He has over 25 years of experience in diverse sectors, from manufacturing and financial services to the public sector and managed IT services.
With particular expertise in Microsoft and Linux technologies, he has interest in PowerShell on both platforms. An advocate of a common-sense approach to coding, best practice, and code reusability, he enjoys practicing what he preaches in his code and mentoring new professionals.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787126307.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the color images of this book
Errata
Piracy
Questions
Introduction to PowerShell
What is PowerShell?
Quick reference
Comments
Special characters
Tick in PowerShell
Common operators
Dropping unwanted output
Creating arrays and hashtables
Strings
Common reserved variables
Quick commands and hot keys
PowerShell editors
PowerShell ISE
Features
Installing ISE Preview
Starting ISE
Visual Studio Code
Features
Console
Version control (Git)
PowerShell on Linux
Installing PowerShell
Where are the PowerShell files?
Changing the shell
Profiles
Multiplatform scripting
Line endings
File encoding
Path separator
Example
Summary
Working with PowerShell
Getting help
Updatable help
The Get-Help command
Syntax
Examples
Parameter
Detailed and Full switches
Save-Help
Update-Help
About help files
Command naming and discovery
Verbs
Nouns
Finding commands
Aliases
Parameters and parameter sets
Parameters
Optional parameters
Optional positional parameters
Mandatory parameters
Mandatory positional parameters
Switch parameters
Common parameters
Parameter values
Parameter sets
Confirm, WhatIf, and Force
Confirm parameter
ConfirmPreference
WhatIf parameter
WhatIfPreference
Force parameter
Providers
Drives using providers
Using providers
Summary
Modules and Snap-Ins
What is a module?
What is the PowerShell Gallery?
The Get-Module command
The Import-Module command
The Remove-Module command
The Find-Module command
The Install-Module command
The Save-Module command
What is a snap-in?
Using snap-ins
Summary
Working with Objects in PowerShell
Pipelines
Standard output
Non-standard output
The object pipeline
Members
The Get-Member command
Accessing properties
Using methods
Access modifiers
The Add-Member command
Enumerating and filtering
The ForEach-Object command
Where-Object command
Selecting and sorting
The Select-Object command
The Sort-Object command
Grouping and measuring
The Group-Object command
The Measure-Object command
Comparing
Importing, exporting, and converting
The Export-Csv command
The Import-Csv command
Export-Clixml and Import-Clixml
Summary
Operators
Arithmetic operators
Operator precedence
Addition and subtraction operators
Multiplication, division, and modulus operators
Shift left and shift right operators
Assignment operators
Assign, add and assign, and subtract and assign
Multiply and assign, divide and assign, and modulus and assign
Comparison operators
Case-sensitivity
Comparison operators and arrays
Equal to and not equal to
Like and not like
Greater than and less than
Contains and in
Regular-expression-based operators
Match and not match
Replace
Split
Binary operators
Binary and
Binary or
Binary exclusive or
Binary not
Logical operators
And
Or
Exclusive or
Not
Type operators
As
Is and isnot
Redirection operators
Redirection to a file
Redirecting streams to standard output
Redirection to null
Other operators
Call
Comma
Format
Increment and decrement
Join
Summary
Variables, Arrays, and Hashtables
Naming and creating variables
Variable commands
Clear-Variable
Get-Variable
New-Variable
Remove-Variable
Set-Variable
Variable scope
Local and Global scope
Private scope
Script scope
Type and type conversion
Objects assigned to variables
Arrays
Creating an array
Arrays with a type
Adding elements to an array
Selecting elements from an array
Changing element values in an array
Removing elements from an array
Removing elements by index
Removing elements by value
Clearing an array
Filling variables from arrays
Multi-dimensional and jagged arrays
Hashtables
Creating a hashtable
Adding and changing elements to a hashtable
Selecting elements from a hashtable
Enumerating a hashtable
Removing elements from a hashtable
Lists, dictionaries, queues, and stacks
Lists
Creating a list
Adding elements to the list
Selecting elements from the list
Removing elements from the list
Changing element values in a list
Dictionaries
Creating a dictionary
Adding and changing elements in a dictionary
Selecting elements from a dictionary
Enumerating a dictionary
Removing elements from a dictionary
Queues
Creating a queue
Enumerating the queue
Adding elements to the queue
Removing elements from the queue
Stacks
Creating a stack
Enumerating the stack
Adding elements to the stack
Removing elements from the stack
Summary
Branching and Looping
Conditional statements
If, else, and elseif
Assignment within if statements
Switch
Wildcard and Regex
Expressions
Loops
Foreach
For
Do until and do while
While
Break and continue
Summary
Working with .NET
Assemblies
Namespaces
Types
Classes
Constructors
Calling constructors
Calling constructors with lists of arguments
Arguments as an array
Properties and methods
Static properties
Static methods
Non-public classes
Type accelerators
Using
Using assemblies
Using namespaces
Summary
Data Parsing and Manipulation
String manipulation
Indexing into strings
String methods and arrays
Substring
Split
Replace
Trim, TrimStart, and TrimEnd
Insert and Remove
IndexOf and LastIndexOf
PadLeft and PadRight
ToUpper, ToLower, and ToTitleCase
Contains, StartsWith, and EndsWith
Chaining methods
Converting strings
Working with Base64
How Base64 works
Working with CSV
Convert-String
ConvertFrom-String
Number manipulation
Large byte values
Power-of-10
Hexadecimal
Using System.Math
Converting strings to numeric values
Date and time manipulation
DateTime parameters
Parsing dates
Changing dates
Comparing dates
Summary
Regular Expressions
Regex basics
Debugging regular expressions
Literal characters
Any character (.)
Repetition with * and +
The escape character (\)
Optional characters
Non-printable characters
Anchors
Repetition
Exploring the quantifiers
Character classes
Ranges
Negated character class
Character class subtraction
Shorthand character classes
Alternation
Grouping
Repeating groups
Restricting alternation
Capturing values
Named capture groups
Non-capturing groups
Examples of regular expressions
MAC addresses
IP addresses
Netstat command
Summary
Files, Folders, and the Registry
Working with providers
Navigating
Getting items
Drives
Items
Testing existence
Creating and deleting items
Invoking items
Item properties
Filesystem properties
Adding and removing file attributes
Registry values
Permissions
Ownership
Access and audit
Rule protection
Inheritance and propagation flags
Removing access control entries
Copying lists and entries
Adding access control entries
Filesystem rights
Registry rights
Transactions
File catalogs
New-FileCatalog
Test-FileCatalog
Summary
Windows Management Instrumentation
Working with WMI
WMI classes
WMI commands
The WMI Query Language
Understanding SELECT, WHERE, and FROM
Escape sequences and wildcard characters
Logic operators
Comparison operators
Quoting values
Associated classes
WMI object path
Using ASSOCIATORS OF
CIM cmdlets
Getting instances
Getting classes
Calling methods
Creating instances
Working with CIM sessions
Associated classes
The WMI cmdlets
Getting instances
Working with dates
Getting classes
Calling methods
Creating instances
Associated classes
Permissions
Sharing permissions
Creating a shared directory
Getting a security descriptor
Adding an access control entry
Setting the security descriptor
WMI permissions
Getting a security descriptor
The access mask
WMI and SDDL
Summary
HTML, XML, and JSON
HTML
ConvertTo-Html
Multiple tables
Adding style
HTML and special characters
XML
Elements and attributes
Namespaces
Schemas
System.Xml
ConvertTo-Xml
XML type accelerator
XPath and Select-Xml
Working with namespaces
Creating documents
Modifying element and attribute values
Adding elements
Copying nodes between documents
Removing elements and attributes
Schema validation
System.Xml.Linq
Opening documents
Selecting nodes
Creating documents
Working with namespaces
Modifying element and attribute values
Adding nodes
Removing nodes
Schema validation
JSON
ConvertTo-Json
ConvertFrom-Json
Summary
Working with REST and SOAP
Web requests
HTTP methods
HTTPS
Bypassing SSL errors
Capturing SSL errors
Working with REST
Invoke-RestMethod
Simple requests
Requests with arguments
Working with authentication
Walking through OAuth
Creating an application
Getting an authorization code
Requesting an access token
Getting a list of playlists
Getting a list of tracks
Working with SOAP
New-WebServiceProxy
Methods
Types
Namespaces
Summary
Remoting and Remote Management
WS-Management
Enabling remoting
Get-WSManInstance
WSMan drive
Remoting and SSL
Set-WSManQuickConfig
Remoting and permissions
Remoting permissions GUI
Remoting permissions by script
User Account Control
Trusted hosts
CIM sessions
New-CimSession
Get-CimSession
Using CIM sessions
PS sessions
New-PSSession
Get-PSSession
Invoke-Command
Local functions and remote sessions
Using splatting with ArgumentList
The AsJob parameter
Disconnected sessions
The using variable scope
Enter-PSSession
Import-PSSession
Export-PSSession
Copying items between sessions
The double-hop problem
CredSSP
Passing credentials
Summary
Testing
Static analysis
Abstract syntax tree
PSScriptAnalyzer
Suppressing rules
Testing with Pester
Why write tests?
What to test
Describe and It
Test cases
Independent verification
Assertions
Be
BeIn
BeLessThan
BeLike
BeLikeExactly
BeNullOrEmpty
BeOfType
FileContentMatch
FileContentMatchExactly
FileContentMatchMultiline
Exist
Match
MatchExactly
Throw
Not
Context
Before and After
TestDrive
Mock
Assert-MockCalled
Parameter filtering
Mocking objects
Fabricating objects
Mocking methods
CIM objects
Pester in practice
Summary
Error Handling
Error types
Terminating errors
Non-terminating errors
Error action
Raising errors
Error records
Write-Error
Throw and ThrowTerminatingError
Error and ErrorVariable
Catching errors
Try, catch, and finally
Try
Catch
Finally
Rethrowing errors
Inconsistent error behavior
Throw and ErrorAction
Nesting try-catch-finally
Terminating or non-terminating
Trap
Using trap
Trap, scope, and continue
Summary
PowerShell scripts offer a handy way to automate various chores. Working with these scripts effectively can be a difficult task. This comprehensive guide starts from scratch and covers advanced-level topics, along with tips to make you a PowerShell scripting expert.
Chapter 1, Introduction to PowerShell, introduces PowerShell and why it is applicable to the IT community. This chapter discusses the types of Microsoft systems that leverage PowerShell and why it's important to learn this scripting language.
Chapter 2, Working with PowerShell, talks about finding and using commands and parameters.
Chapter 3, Modules and Snap-Ins, shows how to use PowerShell modules and snap-ins.
Chapter 4, Working with Objects in PowerShell, shows how to work with objects in PowerShell.
Chapter 5, Operators, shows how to use operators to test and manipulate data.
Chapter 6, Variables, Arrays, and Hashtables, explains the different mechanisms within PowerShell that are able to store data. These include variables, hashes, and arrays.
Chapter 7, Branching and Looping, shows how to explore conditional statements and how to implement loops in PowerShell.
Chapter 8, Working with .NET, shows how to work with existing classes from the .NET framework in PowerShell.
Chapter 9, Data Parsing and Manipulation, explains different methods to manipulate simple types in PowerShell.
Chapter 10, Regular Expressions, shows the usage of regular expressions in PowerShell scripts. This will provide the user with the ability to provide quick data comparisons.
Chapter 11, Files, Folders and the Registry, explores different methods to interact with common items on the file system and registry.
Chapter 12, Windows Management Instrumentation, explores PowerShell’s ability to interact with WMI. This includes methods by which users can manipulate the WMI to obtain information pertaining to an operating system.
Chapter 13, HTML, XML, and JSON, explores the XML structure and how PowerShell can interact with XML files. This chapter will also explore how to use XML files as answer files for PowerShell scripts.
Chapter 14, Working with REST and SOAP, shows how to use REST or SOAP interfaces.
Chapter 15, Remoting and Remote Management, explores the use of Windows remoting and remote sessions to execute against remote systems.
Chapter 16, Testing, shows how to use PSScriptAnalyzer and Pester to improve the quality of your code.
Chapter 17, Error Handling, shows how to leverage PowerShell’s error handling to work with errors.
For this book, you will need Windows 7 or 10 and PowerShell 5.0 or 5.1. Nothing else is mandatory or used.
If you are a system administrator who wants to become an expert in controlling and automating your Windows environment, then this book is for you. It is also for those new to the PowerShell language.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringWindowsPowerShellScriptingSecondEdition_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
I write this as PowerShell approaches its 10th birthday since its release. PowerShell has come a long way since that time.
For me, PowerShell has gone from being a speculative replacement for a mixture of VBScript, C#, and Perl to a complex language with a great community.
This book is split into a number of sections. Much of the book is intended to act as a reference. We will cover the following topics in this book:
Exploring PowerShell fundamentals
Working with data
Automating with PowerShell
Extending PowerShell
In the first section of this book, while exploring the PowerShell fundamentals, we will look at the use of language and cover as many building blocks as possible.
In this chapter, we will briefly look at a number of short, diverse topics:
What is PowerShell?
Quick reference
PowerShell editors
PowerShell on Linux
PowerShell is a mixture of a command line, a functional programming language, and an object-oriented programming language. PowerShell is based on Microsoft .NET, which gives it a level of open flexibility that was not available in Microsoft's scripting languages (such as VBScript or batch) before this.
PowerShell is an explorer's scripting language. With built-in help, command discovery, and with access to much of the .NET Framework, it is possible to dig down through the layers.
This book is based on PowerShell 5.1; some of the features discussed in the book may not be available in the earlier versions of PowerShell.
There is a wide variety of quick references available for PowerShell. This particular reference is intended to kick-start the book, as a lot of this is either not explicitly explained or used often before in a more detailed explanation.
Refer to the following table:
Line comment
#
# This is a line comment
Block comment
<#
#>
<#
This is a block or multi-line comment
#>
Refer to the following table:
Statement separator
;
Get-Command Get-Process; Get-Command Get-Help
Call operator
&
& ‘Get-Process’ # Invoke the string as a command
& { Get-Process –Id $PID } # Invoke the script block
Dot-source operator
.
. C:\script.ps1 # Execute the script in the current scope (instead of its own scope)
PowerShell uses a tick as a multipurpose escaped character.
A tick may be used as a line continuation character. Consider the following example:
'one' -replace 'o', 't' ` -replace 'n', 'w' ` -replace 'e', 'o'
When using a tick to split a long statement across several lines, the tick must be the last character (it cannot be followed by a space or any other character).
A tick is used to construct several characters that can be used in strings:
Description
String
ASCII character code
Null
`0
0
Bell sound
`a
7
Backspace
`b
8
New page form feed
`f
12
Line feed
`n
10
Carriage return
`r
13
Horizontal tab
`t
9
Vertical tab
`v
11
The tab character, for example, may be included in a string:
PS> Write-Host "First`tSecond" First Second
Alternatively, the bell sound may be played in the PowerShell console (but not ISE):
Write-Host "`a"
Refer to the following table:
Equal to
-eq
1 –eq 1 # Returns $true
1 –eq 2 # Returns $false
Not equal to
-ne
1 –ne 2 # Returns $true
1 –ne 1 # Returns $false
And
-and
$true –and $true # Returns $true
$true –and $false # Returns $false
$false –and $false # Returns $false
Or
-or
$true –or $true # Returns $true
$true –or $false # Returns $true
$false –or $false # Returns $false
Addition and concatenation
+
1 + 1 # Equals 2
“one” + “one” # Equals oneone
Subexpression operator
$( )
“Culture is $($host.CurrentCulture)”
“Culture is $(Get-Culture)”
Refer to the following table:
ise
ise <file>
Opens PowerShell ISE.
Opens a file with ISE if a filename is given.
code
code <file or folder>
If Visual Studio Code is installed (and in %PATH%).
Opens the VS Code.
Opens a file or folder with the VS Code.
Get-History
history
Shows command history for the current session.
<Text><Tab>
Autocompletes in context. Tab can be used to complete command names, parameter names, and some parameter values.
#<Text><Tab>
Autocompletes against history (beginning of the line). Typing#get-and repeatedly pressingTabwill cycle through all commands containingGet-from your history.
ii
ii
is an alias for the
invoke-item
. Opens the current directory in Explorer.
start iexplore
start is an alias for the start-process. Opens Internet Explorer.
start <name> -verb runas
Runs a process as administrator.
While it is possible to write for PowerShell using the Notepad application alone, it is rarely desirable. Using an editor designed to work with PowerShell can save a lot of time.
Specialized PowerShell editors, at a minimum, offer automatic completion (IntelliSense) that reduces the amount of cross-referencing required while writing code. Finding a comfortable editor early is a good way to ease into PowerShell: memorizing commands and parameters is not necessary.
Two editors are discussed, as follows:
PowerShell ISE
Visual Studio Code
PowerShell IntegratedScriptingEnvironment (ISE) was introduced with PowerShell 2 in October 2009 and has been updated with every subsequent release.
ISE has an immediate advantage over other editors. It is installed along with PowerShell itself and is likely to be available in some form wherever PowerShell is. ISE consists of a text editor pane and a script pane, as shown in the following screenshot:
ISE is a rich editing environment that includes IntelliSense, built-in help, syntax checking, debugging, and so on.
Additional features are available for ISE from the following add-on tools website:
http://social.technet.microsoft.com/wiki/contents/articles/2969.windows-powershell-ise-add-on-tools.aspx
If you are developing code for use on production systems, I strongly recommend adding PS Script Analyzer. PS Script Analyzer will highlight areas of your code that do not conform to its rule set; for example, using an alias instead of a command name would be highlighted.
Community and commercial add-ons can greatly extend the functionality of ISE to simplify day-to-day use.
In PowerShell 5, the distribution model for ISE is in the process of changing. Until version 5, ISE was released as a part of the Windows Management Framework (WMF). New features were introduced with each version of WMF, but the time between the versions was long.
ISE Preview may be installed from the PowerShell gallery using the following command:
Install-Module -Name PowerShellISE-Preview
Once installed, the update-module command may be used to bring ISE up to par with the published version.
ISE Preview can coexist with the version of ISE installed by the WMF package.
ISE may be started from the start menu; however, running the powershell_isecommand (from the Run dialog, cmd, or the search box) is sufficient. In PowerShell, the simpler isecommand is aliased to powershell_ise.exe.
If the preview version from the PowerShell gallery is being used, the following command will start that version of ISE:
Start-ISEPreview
This first preview version differs a little from the version of ISE shipping with WMF 5. If the distribution model is successful, the PowerShell team hopes to release a new version of ISE every month, with each release fixing bugs and/or adding new features.
Visual Studio Code is a free open source editor published by Microsoft. VS Code may be downloaded from http://code.visualstudio.com.
VS Code is a good choice of editor when working with multiple languages or when specifically looking for an editor that supports Git in a simple manner.
VS Code does not come with the native PowerShell support. It must be added. Once VS Code is installed, open it, and select the EXTENSIONS button on the left-hand side.
Type PowerShell in the search dialog box, and install the PowerShell language support:
After installation, the extension provides Syntax highlighting, testing using PowerShell Script Analyzer, debugging, and so on.
Unlike ISE, the console (or terminal, as it is named) in VS Code must be configured. By default, the terminal in code uses cmd.exe.
The following process is used to make the terminal use PowerShell:
Open
User
Settings
from
File
and
Preferences
. The same may be achieved by pressing
F1
and typing
user settings
followed by return.
This opens two windows: a
Default Settings
file on the left and a
settings.json
on the right. The file on the right holds user-specific configuration that overrides or adds to the default.
Expand the
Integrated Terminal
section in
Default Settings
(by clicking on the
o9
symbol) to show the default values.
On the right-hand side, enter the following between the curly braces:
"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe"
Save the changes, then press
Ctrl
+
Shift
+
'
(apostrophe) to open a new PowerShell terminal.
Ctrl
+
'
(apostrophe) toggles the visibility of the terminal window.
Visual Studio Code comes with integrated support for Git version control. Git is a distributed version control system; each developer has a copy of the same repository.
Setting up a repository is simple, as follows:
Open a folder that contains a project. Then, select the
Git
button (or press
Ctrl
+
Shift +
G
).
Click on
Initialize git repository
button as shown in the following screenshot:
Once you have done this, files may be added to version control when committing (applying a change).
Subsequent changes to files may be inspected before committing again:
PowerShell for Linux is, at least at the time of writing, in alpha. The current release is still worth installing even if only to see what having a unified shell may look like.
Some familiarity with Linux is assumed during this process.
This installation is based on PowerShell 6, alpha 12 as the latest at the time of writing. The package can be downloaded from GitHub with yum, which will also install the dependencies (https://github.com/PowerShell/PowerShell/releases/latest):
The following command will install PowerShell and any dependencies (
libicu
,
libunwind
, and
uuid
):
sudo yum install https://github.com/PowerShell/PowerShell/releases/download/v6.0.0-alpha.12/powershell-6.0.0_alpha.12-1.el7.centos.x86_64.rpm
alpha 12 is the latest release but it may not be when you read this.
PowerShell can be immediately started by running the following command:
powershell
Create a few files in the
home
directory as a test:
Set-Location ~ 1..10 | ForEach-Object { New-Item $_ -ItemType File }
The previous command creates
10
empty files named
1
to
10
(with no file extension). Ensure that the new files are now visible using
Get-ChildItem
:
Get-ChildItem
Several of the following used paths are specific to the installed release (in this case, alpha 12).
As with PowerShell on Windows, the PSHOME variable shows where PowerShell itself has been installed:
PS> $PSHOME /opt/microsoft/powershell/6.0.0-alpha.12
The paths for module installation may be viewed using the environment variables:
PS> $env:PSMODULEPATH -split ':' /home/psuser/.local/share/powershell/Modules /usr/local/share/powershell/Modules /opt/microsoft/powershell/6.0.0-alpha.12/Modules
Once installed, PowerShell is visible in the list of available shells:
chsh -l
Set PowerShell as the default shell for the current user:
chsh New shell [/bin/bash]: /usr/bin/powershell
The current user profile on Linux resides under the home directory:
~/.config/powershell
Two profiles can be created: CurrentUserCurrentHost (Microsoft.PowerShell_profile.ps1) and Current User (profile.ps1). Inspecting the automatic variable, $PROFILE shows the first of these:
The directory will need to be created prior to use; the following command creates it:
New-Item ~/.config/powershell -ItemType Directory
Create a simple profile file by sending a string to a file:
‘Write-Host “Welcome to PowerShell” -ForegroundColor Green’ |
Out-File .config/powershell/profile.ps1
The
AllUser
profile may be created under PowerShell's installation directory, in this case, alpha 12, as this is the version I have installed:
/opt/microsoft/powershell/6.0.0-alpha.12
Writing to this area of the filesystem requires the
root
privileges:
sudo vi /opt/microsoft/powershell/6.0.0-alpha.12/profile.ps1
Inside
vi
, press
i
to enter insert mode and then type the following:
Write-Host 'This is the system profile' -ForegroundColor Yellow
Once completed, press
Esc
, then type
:wq
to save and quit
vi
.
As with PowerShell on Windows, this will be executed before a user-level
profile
that shows the following in the console when the shell is started:
This is the system profile Welcome to PowerShell
PowerShell on Linux (and macOS) has a long way to go to reach maturity. Our experience writing for these systems has to make a similar journey.
One of the most important facets is that Linux and macOS run PowerShell Core. It lacks some features we may have become used to when writing for Windows.
Windows editors, including ISE, tend to use a carriage return followed by linefeed (\r\n or `r`n) at the end of each line. Linux editors use linefeed only (\n or `n).
Line endings are less important if the only thing reading the file is PowerShell (on any platform). However, if a script is set to executable on Linux, a sha-bang must be included and the line-ending character used must be linefeed only.
For example, a created as follows named test.ps1 must use \n to end lines:
#!/usr/bin/env powershell Get-Process
The first line is the sha-bang and lets Linux know which parser to use when executing the shell script.
Once created, chmod may be used to make the script executable outside of PowerShell:
chmod +x test.ps1
After being made executable, the script may be executed from bash with the full path or a relative path:
./test.ps1
Windows editors, including ISE, tend to save files using what is commonly known as ANSI encoding; this is more correctly known as Windows-1252.
As Windows-1252 is a Microsoft native format, it may be more appropriate to save files in a universally accepted format such as UTF8.
Testing shows that PowerShell on Linux is forgiving about path separators; that is, Microsoft Windows uses the backslash (\), where Linux uses a forward slash (/).
If anything outside of PowerShell (including native commands) is to be used, a correct separator should be chosen.
The Join-Path command will merge path elements using the correct separator for each platform. Manual path construction (based on merging strings) should be avoided.
This chapter featured a brief introduction to PowerShell itself and provided a quick reference for some of the syntax and features.
A reasonable PowerShell editor is a great tool to have for any scripting language. A number of excellent options are available for beginners and veterans alike.
Recently, PowerShell has moved onto GitHub as an open source project. At the same time, versions of PowerShell for Linux and macOS have been developed. Installation of PowerShell on CentOS was briefly demonstrated.
In Chapter 2, Working with PowerShell, we will look at the help system and how to discover commands.
A grasp of a few basics about PowerShell will go a long way. These basics will always be useful no matter how long you work with the language.
In this chapter, we will cover the following topics:
Getting help
Command naming
Command discovery
Parameters and parameter sets
Providers
Gaining confidence using the built-in help system is an important part of working with PowerShell. In PowerShell, help is extensive; authors can easily write their own help content when working with scripts and script modules.
A number of commands are available to interact with the help system, as follows:
Get-Help
Save-Help
Update-Help
Before exploring these commands, the concept of updatable help should be discussed.
Updatable help was introduced with PowerShell 3. It gives authors the option to store the most recent versions of their help documentation outside of PowerShell on web servers.
Help for the core components of PowerShell is no longer a part of the Windows Management Framework package and must be downloaded before it can be viewed. The first time Get-Help is run, you will be prompted to update help.
If the previous prompt is accepted, PowerShell will attempt to download content for any module that supports updatable help.
Computers with no internet access or computers behind a restrictive proxy server may not be able to download the help content. If PowerShell is unable to download help, it can only show a small amount of discoverable information about a command; for example, without downloading help, the content for the Out-Null command is minimal, as shown in the following code:
PS C:\windows\system32> Get-Help Out-Null
NAME
Out-Null
SYNTAX
Out-Null [-InputObject <psobject>] [<CommonParameters>]
ALIASES
None
REMARKS
Get-Help cannot find the Help files for this cmdlet on this computer.
It is displaying only partial help.
-- To download and install Help files for the module that
includes this cmdlet, use Update-Help.
-- To view the Help topic for this cmdlet online, type:
"Get-Help Out-Null -Online" or go to
http://go.microsoft.com/fwlink/?LinkID=113366
.
Updatable helps as a help file that may be viewed using the following command:
Get-Help about_Updatable_Help
Without any arguments or parameters, Get-Help will show introductory help about the help system. This content is taken from the default help file (Get-Help default); a snippet of this is as follows:
PS> Get-Help
TOPIC
Windows PowerShell Help System
SHORT DESCRIPTION
Displays help about Windows PowerShell cmdlets and concepts.
LONG DESCRIPTION
Windows PowerShell Help describes Windows PowerShell cmdlets,
The previous command is equivalent to running Get-Help and piping it into the more command:
Get-Help default | more
Alternatively, Get-Help can be asked to show a window:
Get-Help default -ShowWindow
The available help content may be listed using either of the following two commands:
Get-Help * Get-Help -Category All
Help for a command may be viewed as follows:
Get-Help <CommandName>
Let's look at an example:
Get-Help Get-Variable
The help content is broken down into a number of visible sections: name, synopsis, syntax, description, related links, and remarks. Syntax is covered in the following section in more detail as it is the most complex.
The syntax section lists each of the possible combinations of parameters a command will accept; each of these is known as a parameter set.
A command that has more than one parameter set is displayed as follows:
SYNTAX
Get-Process [[-Name] <String[]>] [-ComputerName <String[]>]
[-FileVersionInfo] [-Module] [<CommonParameters>]
