Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Windows PowerShell Scripting (Second Edition)

You're reading from   Mastering Windows PowerShell Scripting (Second Edition) One-stop guide to automating administrative tasks

Arrow left icon
Product type Paperback
Published in Oct 2017
Publisher Packt
ISBN-13 9781787126305
Length 440 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Chris Dent Chris Dent
Author Profile Icon Chris Dent
Chris Dent
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Preface 1. Introduction to PowerShell FREE CHAPTER 2. Working with PowerShell 3. Modules and Snap-Ins 4. Working with Objects in PowerShell 5. Operators 6. Variables, Arrays, and Hashtables 7. Branching and Looping 8. Working with .NET 9. Data Parsing and Manipulation 10. Regular Expressions 11. Files, Folders, and the Registry 12. Windows Management Instrumentation 13. HTML, XML, and JSON 14. Working with REST and SOAP 15. Remoting and Remote Management 16. Testing 17. Error Handling

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.
You have been reading a chapter from
Mastering Windows PowerShell Scripting (Second Edition) - Second Edition
Published in: Oct 2017
Publisher: Packt
ISBN-13: 9781787126305
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime