Book Image

Mastering Windows PowerShell Scripting (Second Edition) - Second Edition

By : Brenton J.W. Blawat
Book Image

Mastering Windows PowerShell Scripting (Second Edition) - Second Edition

By: Brenton J.W. Blawat

Overview of this book

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.
Table of Contents (24 chapters)
Title Page
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Quick reference


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.

Comments

Refer to the following table:

Line comment

#

# This is a line comment

Block comment

<#

#>

<#
This is a block or multi-line comment
#>

Special characters

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)

Tick in PowerShell

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"

Common operators

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)”

Dropping unwanted output

Refer to the following table:

Assign to null

$null = Expression

$null = Get-Command

Cast to void

[Void](Expression)

[Void](Get-Command)

Pipe to Out-Null

Expression | Out-Null

Get-Command | Out-Null

Redirect to null

Expression > $null

Get-Command > $null

Creating arrays and hashtables

Refer to the following table:

Using the array operator

@()

$array = @()    # Empty array
$array = @(1, 2, 3, 4)

Implicit array

Value1, Value2, Value3

$array = 1, 2, 3, 4
$array = “one”, “two”, “three”, “four”

Using the hashtable operator

@{}

$hashtable = @{}    # Empty hashtable
$hashtable = @{Key1 = “Value1”}
$hashtable = @{Key1 = “Value1”; Key2 = “Value2”}

Strings

Refer to the following table:

Expanding string

“ “

“Value”
$greeting = “Hello”; “$greeting World”   # Expands variable

Expanding here-string

@”

“@

$one = ‘One’
@”
Must be opened on its own line.
This string will expand variables like $var.
Can contain other quotes like “ and ‘.
Must be closed on its own line with no preceding white space.
“@

Non-expanding string

‘ ‘

‘Value’
‘$greeting World’    # Does not expand variable

Non-expanding here-string

@’

‘@

@’
Must be opened on its own line.
This string will not expand variables like $var.
Can contain other quotes like “ and ‘.
Must be closed on its own line with no preceding white space.
‘@

Quotes in strings

“ `” “

“ ““ “

‘ `’ ‘

‘ ‘‘ ‘

“Double-quotes may be escaped with tick like `”.”
“Or double-quotes may be escaped with another quote ““.”
‘Single-quotes may be escaped with tick like `’.’
‘Or single-quotes may be escaped with another quote like ‘‘.’

Common reserved variables

Refer to the following table:

Errors

$Error

$Error[0]    # The last error

Formats the enumeration limit. Dictates the number of elements displayed for objects with properties based on arrays.

The default is 4.

$FormatEnumerationLimit

$object = [PSCustomObject]@{
Array = @(1, 2, 3, 4, 5)
}
$object    # Shows 1, 2, 3, and 4
$formatenumerationlimit = 1
$object    # Shows 1

Holds data of the current PowerShell host.

$Host

$host
$host.UI.RawUI.WindowTitle

The matches found when using the -match operator.

$Matches

‘text’ –match ‘.*’
$matches

The output field separator.

The default is a single space.

Dictates how arrays are joined when included in an expandable string.

$OFS

$arr = 1, 2, 3, 4
“Joined based on OFS: $arr”
$ofs = ‘, ‘
“Joined based on OFS: $arr”

Current PowerShell process ID.

$PID

Get-Process –Id $PID

Holds the path to each of the profile files.

$PROFILE

$profile.AllUsersAllHosts
$profile.AllUsersCurrentHost
$profile.CurrentUserAllHosts
$profile.CurrentUserCurrentHost

PowerShell version information.

$PSVersionTable


$PSVersionTable.PSVersion

Present working directory.

$PWD

$PWD.Path

Quick commands and hot keys

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 pressing Tab will cycle through all commands containing Get- 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.