Strings And Quotes
Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 8 of 28.
A string is text. PowerShell has two kinds of quotes, and they behave differently.
In double quotes, a variable is replaced by its value. For anything more than a plain variable, such as a calculation or a property, put it inside $( ):
$city = "Lima"
$days = 4
Write-Output "Trip to $city for $days days"
Write-Output "Hours: $($days * 24)"
Write-Output 'Saved as $city'Trip to Lima for 4 days
Hours: 96
Saved as $citySingle quotes keep the text exactly as written, $ included. Without $( ), "Hours: $days * 24" prints Hours: 4 * 24.
Inside double quotes the backtick ` is the escape character: `n is a new line, `t a tab, `" a quote and `$ a dollar sign. A string's .Length is its number of characters: "Lima".Length is 4.
Challenge
EasyPrint a shopping cart summary with strings.
- Create
$namewith the textMaya,$itemswith3and$pricewith4.5. - In one double-quoted string, print
Maya has 3 items in the cart, with the name and the count coming from the variables. - Print
Total:followed by$itemstimes$price, computed inside the string with$( ). - Print the text
Type $name to use a variableexactly as written,$nameincluded.
Your script prints:
Maya has 3 items in the cart
Total: 13.5
Type $name to use a variableTry it yourself
$name = "Maya"
$items = 3
$price = 4.5
# Print the three lines
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check