Strings Arrays and Hashtables Flashcards
We create a verbatim string by using…
Double quotes or single quotes.
How can we escape a double quote or single quote when creating a verbatim string?
Double up the double quote or single quote. Eg:
“I just wanted to say ““Hello World””, ok?”
‘I can’‘t believe this’
What is the escape sequence for strings (e.g. new line etc)
Back tick - `
What are the escape sequences for: Backspace New Line Carriage Return CrLf Tab
`b (doesn't work in ISE, only regular script window) `n `r `r`n `t
What are Here Strings?
strings that split out over a number of lines: $heretext = @" Here is some text "@
What are the rules regarding placement of the @” and “@ character sequences with regard to here strings?
@” has to be that the last character sequence at the end of the line (typically just after a variable declaration). The “@ characters have to be at the beginning of a new line.
When using here strings, is it necessary to use doubled quotes?
No
What is string interpolation?
The ability to dynamically resolve variables within a string. E.g:
$hello = “Hello World”
“This is my greeting: $hello”
How can we directly access a collection of items (e.g. Get-ChildItem) ?
Wrap the command in parentheses. E.g.
(Get-ChildItem).Count
How do we actually display the name of a variable within a string?
Use backtick: E.g.
$items = (Get-ChildItem).Count "`$items = $items"
returns “$items = 123”
Does string interpolation work with single quotes?
NO!
Does string interpolation work with here strings?
Yes :)
How do we embed expressions within a string?
Wrap the expression in $(). E.g
“There are $((Get-ChildItem).Count) items in $(Get-Location)”
How do we get the current date/time in PS?
Get-Date
How can we format strings using C# - esque format?
Use the static Format method of string. E.g.
What’s the PS shortcut for [string]::Format()?
Use -f . E.g.
“There are {0} items” -f $itemCount
“There are {0} items in {1}” -f $itemCount, $location
Why would you use -f formatting rather than string interpolation?
For formatting, e.g. dates, currencies etc
How do you specify number of decimal places for number formatting?
{0:N[# of places]}. E.g.
“{0:N0}” -f 123.34 # returns 123
“{0:N1}” -f 123.34 # returns 123.3
“{0:N2}” -f 123.34 # returns 123.34
“{0:N3}” -f 123.34 # returns 123.340