Chapter 18. Variables: a place to store your stuff

 

We’ve already mentioned that PowerShell contains a scripting language, and in a few more chapters we’ll start to play with it. But once you start scripting, you tend to need variables, so we’ll get those out of the way in this chapter. You can use variables in a lot of places other than long, complex scripts, so we’ll also use this chapter to show you some practical ways to use them.

18.1. Introduction to variables

A simple way to think of a variable is as a box in the computer’s memory that has a name. You can put whatever you want into the box: a single computer name, a collection of services, an XML document, and so on. You access the box by using its name, and when accessing it, you can put things in it, add things to it, or retrieve things from it. Those things stay in the box, allowing you to retrieve them over and over.

PowerShell doesn’t place a lot of formality around variables. For example, you don’t have to explicitly announce or declare your intention to use a variable before you do so. You can also change the types of the contents of a variable: One moment you might have a single process in it, and the next moment you can store a bunch of computer names in it. A variable can even contain multiple different things, such as a collection of services and a collection of processes (although we admit that, in those cases, using the variable’s contents can be tricky).

18.2. Storing values in variables

18.3. Using variables: fun tricks with quotes

18.4. Storing many objects in a variable

18.5. More tricks with double quotes

18.6. Declaring a variable’s type

18.7. Commands for working with variables

18.8. Variable best practices

18.9. Common points of confusion

18.10. Lab

18.11. Further exploration

18.12. Lab answers

sitemap