Chapter 16: Variables: A place to store your stuff
Introduces variables as a way to keep PowerShell objects for later use, including outside long scripts.
After this chapter you will be able to
- Purpose and reach of variables. Explain that variables let you store PowerShell objects for later use and are useful beyond long, complex scripts.
- Named reusable storage. Explain a variable as a named place in memory where you can store something and retrieve it repeatedly by name.
- Flexible variable contents. Describe how PowerShell lets you use a variable without declaring it first and change what kind of contents it holds, including storing multiple different things.
- Variable assignment and reuse. Describe how to assign a value to a variable, retrieve it, and use it in place of a value in a command.
- Single and double quoted strings. Distinguish how PowerShell treats a variable name inside single versus double quotation marks. Explain that double quotes replace the variable reference with its contents when the string is parsed.
- Backtick escape character uses. Describe the backtick’s two demonstrated uses: making a dollar sign literal so a variable name is not expanded, and giving `n the special meaning of a new line.
- Comma-separated object collections. Explain how a comma-separated list puts multiple objects in one variable, and why the commas must be outside quoted strings.
- Individual object indexing. Explain how to select one object from a variable by index and how to find the number of objects it contains.
- String properties and methods. Describe how to access a stored object's properties and methods through its variable, and explain what the demonstrated string methods do to the variable's contents.
- Selecting and changing stored objects. Explain why you may need to select a specific object from a variable containing multiple objects before accessing its property or calling its method. Distinguish a method that produces a new string from assigning a new value to an existing object in the variable.
- Methods across stored objects. Trace how a pipeline applies ToLower() to every string in $computers and stores the resulting strings back in the variable.
- Automatic collection unrolling. Explain that when a variable holds multiple objects, PowerShell can access a property or method on the individual objects even if the collection itself lacks that member.
- Subexpressions in double-quoted strings. Explain why a reference such as $processes[0].name does not work as intended when placed directly in a double-quoted string, and how $() lets the string include the expression’s result.
- Declared variable type enforcement. Describe how to declare a variable’s type and what happens when PowerShell can or cannot convert an assigned value. Explain how the variable can later be given a different declared type.
- Ordinary variable syntax. Explain that PowerShell does not require advance variable declarations and that ordinary syntax can create, read, and set variables without variable cmdlets. Describe why normal assignment is generally preferable for editor assistance.
- Clear and concise variable names. Explain why variable names should be meaningful but succinct, and why the section discourages spaces in names.
- Declaring a variable type. Explain when the section recommends declaring a variable’s type and what benefits it gives.
- Variable name parsing. Explain that the dollar sign signals access to a variable’s contents but is not part of its name, and describe how PowerShell determines the name that follows.
- Reusing stored remote connections. Explain why storing a remote connection in a variable could be useful: instead of creating, using, and closing it in one step, you could use the stored connection for several commands.
What it builds on
- What are objects? (chapter 8) · Introduces PowerShell objects.
- Discovering objects: Get-Member (chapter 8) · Using Get-Member to inspect an object.
- Using Enter-PSSession and Exit-PSSession for one-to-one remoting (chapter 13) · Creating and using a connection to a remote computer.
Section by section
Introduction
Introduces variables as a way to keep PowerShell objects for later use, including outside long scripts.
- Purpose and reach of variables: Explain that variables let you store PowerShell objects for later use and are useful beyond long, complex scripts.
Why it matters: This gives you a reason to use variables even when you are not writing a script.
Key terms: variables, objects
16.1 Introduction to variables
This section introduces variables as named, reusable storage in memory and explains PowerShell’s flexible approach to their contents.
- Named reusable storage: Explain a variable as a named place in memory where you can store something and retrieve it repeatedly by name.
Why it matters: This gives you a way to think about keeping a value for later use. - Flexible variable contents: Describe how PowerShell lets you use a variable without declaring it first and change what kind of contents it holds, including storing multiple different things.
Why it matters: You need not decide in advance what kind of object a variable will hold.
Key terms: variable, name, declare, types, objects, array
16.2 Storing values in variables
This section explains how to store simple values in PowerShell variables, retrieve and reuse them, and follow basic naming and lifetime rules.
- Simple values as objects: Explain why a string can be called a simple value even though PowerShell treats it as an object.
Why it matters: It explains why the section talks about storing values without abandoning PowerShell’s object model. - Variable assignment and reuse: Describe how to assign a value to a variable, retrieve it, and use it in place of a value in a command.
Why it matters: Storing a value lets you refer to it again instead of typing it directly into every command. - Changing a variable’s contents: Explain that a variable can later hold a different value, including a value of a different type.
Why it matters: A variable’s earlier contents do not prevent you from replacing them with a different kind of value. - Variable names and session lifetime: Describe the section’s rules and advice for variable names, and state what happens to variables when a shell session closes.
Why it matters: These conventions make variables easier to use and clarify when a stored value will no longer be available.
Key terms: object, System.String, simple value, variable, assignment operator, dollar sign, Get-Member, System.Int32, variable name, curly braces
16.3 Using variables: Fun tricks with quotes
This section explains how quotation marks control variable expansion in PowerShell strings and how the backtick escapes characters.
- Single and double quoted strings: Distinguish how PowerShell treats a variable name inside single versus double quotation marks. Explain that double quotes replace the variable reference with its contents when the string is parsed.
Why it matters: The choice of quotes determines whether a string shows a variable’s name or its value. - Timing of variable expansion: Explain when expansion in a double-quoted string occurs and why changing the original variable later does not update a string already stored in another variable.
Why it matters: An expanded string will not automatically track later changes to the variable used to create it. - Backtick escape character uses: Describe the backtick’s two demonstrated uses: making a dollar sign literal so a variable name is not expanded, and giving `n the special meaning of a new line.
Why it matters: Escapes let you include a variable name literally or insert a line break within a string.
Key terms: single quotation marks, double quotation marks, literal string, replacement action, parses the string, backtick, escape character, `n
16.4 Storing many objects in a variable
This section shows how a comma-separated list stores several distinct objects in one PowerShell variable.
- Comma-separated object collections: Explain how a comma-separated list puts multiple objects in one variable, and why the commas must be outside quoted strings.
Why it matters: Comma placement determines whether the variable holds separate values or one string containing commas.
Key terms: comma-separated list, collections of objects, String types
16.4.1 Working with single objects in a variable
This subsection shows how to access one object in a variable and use its properties and methods.
- Individual object indexing: Explain how to select one object from a variable by index and how to find the number of objects it contains.
Why it matters: Indexing lets you work with a particular object rather than the whole group. - String properties and methods: Describe how to access a stored object's properties and methods through its variable, and explain what the demonstrated string methods do to the variable's contents.
Why it matters: This distinction helps you use a String's methods without assuming they update the stored value.
Key terms: index, square brackets, property, System.String, Length, ToUpper(), ToLower(), Replace()
16.4.2 Working with multiple objects in a variable
This subsection explains how to work with a specific object in a variable containing multiple objects and how to change that object's stored value.
- Selecting and changing stored objects: Explain why you may need to select a specific object from a variable containing multiple objects before accessing its property or calling its method. Distinguish a method that produces a new string from assigning a new value to an existing object in the variable.
Why it matters: It helps you tell the difference between getting a result from one stored object and actually changing what the variable contains.
Key terms: variable, object, property, method, assign
16.4.3 Other ways to work with multiple objects
This subsection shows how to apply a method or select a property across multiple objects stored in a variable.
- Methods across stored objects: Trace how a pipeline applies ToLower() to every string in $computers and stores the resulting strings back in the variable.
Why it matters: This lets you transform every stored object rather than calling a method on just one of them. - Property selection across objects: Describe how Select-Object can select the Length property from each object piped to it.
Why it matters: It gives you a way to inspect the same property across all the stored objects.
Key terms: ForEach-Object, $_, ToLower(), pipeline, Select-Object, Length property
16.4.4 Unrolling properties and methods in PowerShell
This subsection explains how PowerShell automatically accesses properties and methods on the objects held in a variable containing multiple objects.
- Automatic collection unrolling: Explain that when a variable holds multiple objects, PowerShell can access a property or method on the individual objects even if the collection itself lacks that member.
Why it matters: It explains why member access can work on a variable containing multiple objects even when the collection itself lacks that member.
Key terms: collection, property, method, implicitly enumerates, unrolls
16.5 More tricks with double quotes
This section shows how double-quoted strings can include the result of a PowerShell expression or a property from every object in a collection.
- Subexpressions in double-quoted strings: Explain why a reference such as $processes[0].name does not work as intended when placed directly in a double-quoted string, and how $() lets the string include the expression’s result.
Why it matters: A subexpression lets you put a calculated value, rather than just a variable’s contents, into a string. - Collection properties inside double quotes: Describe how referring to a property or method on a collection can produce values from its objects, as illustrated by including process names from $processes in a double-quoted string.
Why it matters: This provides a concise way to include a collection’s property values in a string.
Key terms: double quotes, variable-replacement, subexpression, $(), collection, property, method, enumerate
16.6 Declaring a variable’s type
This section explains how declaring a variable’s type prevents PowerShell from treating input as the wrong kind of data.
- String input and multiplication: Explain why multiplying user input that looks like a number can repeat text instead of doing arithmetic, and how to check the input’s type.
Why it matters: A value that looks numeric can still behave like text. - Declared variable type enforcement: Describe how to declare a variable’s type and what happens when PowerShell can or cannot convert an assigned value. Explain how the variable can later be given a different declared type.
Why it matters: Declaring the expected type helps catch unsuitable values before they cause later logic errors.
Key terms: string, System.String, System.Int32, Get-Member, [int], object type, convert, retype
16.7 Commands for working with variables
This section explains why ordinary variable syntax is usually preferable to variable cmdlets and shows when and how to use those cmdlets.
- Ordinary variable syntax: Explain that PowerShell does not require advance variable declarations and that ordinary syntax can create, read, and set variables without variable cmdlets. Describe why normal assignment is generally preferable for editor assistance.
Why it matters: You can use the simpler syntax you already know without giving up the usual variable operations. - Variable cmdlet usage: Describe the variable cmdlets named here, how to supply a variable name to them, and the particular use identified for Remove-Variable.
Why it matters: If you choose a variable cmdlet, you can pass its name correctly and know the deletion option the section highlights.
Key terms: variable declaration, ad hoc syntax, normal assignment operators, Remove-Variable, Remove-Item, VARIABLE: drive, -name
16.8 Variable best practices
Reviews practical rules for naming variables and declaring their types to make PowerShell code clearer and less error-prone.
- Clear and concise variable names: Explain why variable names should be meaningful but succinct, and why the section discourages spaces in names.
Why it matters: Clear, manageable names make commands and scripts easier to read and write. - Declaring a variable type: Explain when the section recommends declaring a variable’s type and what benefits it gives.
Why it matters: Declaring a consistent object type can catch confusion and make editor assistance more useful.
Key terms: variable names, type of object, declare, code-hinting
16.9 Common points of confusion
This section clarifies what counts as a PowerShell variable name and how the shell identifies it after a dollar sign.
- Variable name parsing: Explain that the dollar sign signals access to a variable’s contents but is not part of its name, and describe how PowerShell determines the name that follows.
Why it matters: Keeping the dollar sign separate from the name helps you read variable references correctly.
Key terms: variable name, dollar sign, opening curly brace, closing curly brace, white space
16.10 Lab
16.11 Lab answers
16.12 Further exploration
This section invites readers to spot opportunities to use variables to reuse values, using a remote connection as an example.
- Reusing stored remote connections: Explain why storing a remote connection in a variable could be useful: instead of creating, using, and closing it in one step, you could use the stored connection for several commands.
Why it matters: Looking for values you use repeatedly helps you recognize when a variable would be handy.
Key terms: variables, connection, remote computers
Where this is used later
- A quick look at scope (chapter 19) · The introduction to PowerShell variables.
- Parameterizing commands (chapter 19) · Uses variable-based values when parameterizing commands.
- Adding the warm and fuzzies with verbose output (chapter 20) · Using variables within double-quoted strings.
- Customizing the prompt (chapter 26) · Using variables in double-quoted strings.
- Foreach (chapter 23) · Uses the idea of storing multiple objects in a variable.
- Enter-PSSession with session objects (chapter 18) · Introduces working with multiple objects stored in a variable.
- -join and -split (chapter 26) · Working with multiple objects stored in a variable
- Validating parameter input (chapter 20) · Provides context for checking that input meets a script’s expectations.
Concepts explained in this chapter
- bindingA variable is a named storage location that holds a value or collection of values and can be assigned a new value.
- stringA string, represented by the .NET System.String type, is a sequence of characters representing text data.
- integerAn integer is a whole number with no fractional or decimal portion.
- assignmentAn assignment operator is a language operator that assigns a value to a variable.
- quotation marksA double quotation mark delimits a PowerShell expandable string in which variable references can be replaced by their values.
- atomic typeA data type defines the kind of value represented and the operations applicable to that value.
- object typeAn object type is the runtime classification that determines an object's available structure and behavior.
- subexpressionA subexpression is an expression nested within a larger expression and evaluated as one operand or component.
- methodA method is a callable operation associated with an object that can direct the object to perform an action.
- collectionA collection is a container that groups multiple values as a single data object.
- Select-ObjectSelect-Object is a PowerShell cmdlet that selects specified properties or creates customized objects from input objects.
- whitespace characterWhitespace is nonprinting spacing such as spaces, tabs, or carriage returns that separates elements in source text.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
