Escape Characters


In PowerShell, if you aren't executing a cmdlet, script, or executable, then you are displaying an expression. In other words, PowerShell parses what you type in either command mode or expression mode. Numbers are treated as numbers and strings should be places in quotes. When you enter a string in quotes, PowerShell echoes it back to you:

 PS C:\> "Hello, Reader" Hello, Reader 

If you don't use quotes, PowerShell assumes you are trying to execute something, so it generates an error:

 PS C:\> Hello,Reader 'Hello' is not recognized as a Cmdlet, function, operable program, or script file. At line:1 char:6 + Hello, <<<< Reader 

You can also use Write-Host to echo what you've typed back to the console. See if you can spot the subtle differences in these two expressions:

 PS C:\> write-host "Hello, Reader" Hello, Reader PS C:\> write-host Hello, Reader Hello Reader PS C:\> 

In the first expression, the phrase "Hello, Reader" is written to the console screen exactly as you typed it into the expression. In the second expression, PowerShell is smart enough to figure out that Hello and Reader are both strings. However, it only writes back the two strings. Notice what's missing. PowerShell thinks the comma is a separator, so it writes back the two strings, which at first glance looks like the first expression. We think you'll be better served though if you use quotes for strings that you want to display. It will make it easier to separate text you have specified versus cmdlet results or expressions.

Occasionally you may want to display a literal value in a string such as the quotes. To accomplish this you need to insert a special escape character, the backward apostrophe `, before the quote characters so they are treated as literal values. The backward apostrophe is technically known as the grace accent

 PS C:\> write-host `"Hello`, Reader`" "Hello, Reader" 

In this example we also escaped the comma since that's part of the string expression and not a PowerShell character. We'll cover formatting output in greater detail in Chapter 9. However, if you need something special such as a beep or a tab, simply use one of PowerShell's escape sequences shown in Table 5-2.

image from book
Table 5-2: Escape Sequences
Open table as spreadsheet

Sequence

Result

`0

(null)

`a

(alert)

`b

(backspace)

`f

(form feed)

`n

(new line)

`r

(carriage return)

`t

(tab)

`v

(vertical quote)

image from book

To see how this works, open a PowerShell window and run the following command:

 PS C:\> Write-Host `a 

Depending on your computer's configuration, a beep should be emitted.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net