Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.
If you own the book already, login here to get free, online, searchable access to the entire book's content.
If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".
PowerShell offers several facilities for working with plain-text data.
To define a literal string (one in which no variable or escape expansion occurs), enclose it in single quotes:
$myString
=
'hello `t $ENV:SystemRoot'
$myString
gets the actual value of hello `t $ENV:SystemRoot
.
To define an expanding string (one in which variable and escape expansion occur), enclose it in double quotes:
$myString
=
"hello
`t
$ENV:SystemRoot"
$myString
gets a value similar to hello C:\WINDOWS
.
To include a single quote in a single-quoted string or a double quote in a double-quoted string, include two of the quote characters in a row:
PS > "Hello ""There""!" Hello "There"! PS > 'Hello ''There''!' Hello 'There'!
To include a complex expression inside an expanding string, use a subexpression. For example:
$prompt
=
"
$(
get-location
)
>"
$prompt
gets a value similar to c:\temp >
.
Accessing the properties of an object requires a subexpression:
$version
=
"Current PowerShell version is:"
$PSVersionTable
.
PSVersion
.
Major
$version
gets a value similar to:
Current PowerShell version is: 3
To define a here string (one that may span multiple lines), place the two characters @"
at the beginning and the two characters "@
on their own line at the end.
For example:
$myHereString
=
@"
This text may span multiple lines, and may
contain "quotes."
"@
Here strings may be of either the literal (single-quoted) or expanding (double-quoted) variety.
PowerShell supports escape sequences inside strings, as listed in Table A-4.
Sequence | Meaning |
---|---|
|
The null character. Often used as a record separator. |
|
The alarm character. Generates a beep when displayed on the console. |
|
The backspace character. The previous character remains in the string but is overwritten when displayed on the console. |
|
The escape character. Marks the beginning of an ANSI escape sequence such as " |
|
A form feed. Creates a page break when printed on most printers. |
|
A newline. |
|
A carriage return. Newlines in PowerShell are indicated entirely by the |
|
A tab. |
|
A unicode character literal. Creates a character represented by the specified hexadecimal Unicode code point such as " |
|
A vertical tab. |
|
A single quote, when in a literal string. |
|
A double quote, when in an expanding string. |
|
That character, taken literally. |