Strings

Windows PowerShell offers several facilities for working with plain-text data.

Literal and Expanding Strings

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 occurs), 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, you may include two of the quote characters in a row:

PS >"Hello ""There""!"
Hello "There"!
PS >'Hello ''There''!'
Hello 'There'!

Tip

To include a complex expression inside of an expanding string, use a subexpression. For example:

$prompt = "$(get-location) >"
$prompt gets a value similar to c:	emp >

Accessing the properties of an object counts as a complex expression:

$output = "Current script name is: $($myInvocation.MyCommand.Path)"

$output gets a value similar to Current script name is c:Test-Script.ps1

Here Strings

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 or expanding variety.

Escape Sequences

Windows PowerShell supports the following escape sequences inside of strings:

Windows PowerShell escape sequences

Sequence

Meaning

`0

The null character.

`a

The alarm character. Generates a beep when displayed on the console.

`b

The backspace character. The previous character remains in the string but is overwritten when displayed on the console.

`f

A form feed. Creates a page break when printed on most printers.

`n

A newline.

`r

A carriage return. Newlines in PowerShell are indicated entirely by the `n character, so this is rarely required.

`t

A tab.

`v

A vertical tab.

’’ (Two single quotes)

A single quote, when in a literal string.

‘’ (Two double quotes)

A double quote, when in an expanding string.

`<any other character>

That character, taken literally.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.221.163