6.3. Using Variables as Parameters

So far I have shown you how to provide literal values as the values for parameters. However, you can also use Windows PowerShell variables as the values for parameters.

I will describe Windows PowerShell variables in more detail in Chapter 10.

A Windows PowerShell variable is named with a dollar sign followed by uppercase or lowercase alphabetic characters, numeric digits, and/or the underscore character.

Do not use the variable $__ in your code. Windows PowerShell uses that variable as an internal variable in pipelines. Scoping of variables often prevents ambiguity for the Windows PowerShell parser, but I strongly recommend that if you use the underscore character it be combined with alphabetic characters or numeric digits in a variable name.

To use a variable as the value of the parameter, you simply provide the variable name where you would provide a literal value.

In this example, I will show you how to use a variable to supply a parameter value to a cmdlet.

In examples earlier in this chapter, you looked for processes that began with w, using the command

get-process w*

You can achieve the same thing using a variable. First, assign the wildcard w* to the variable $a:

$a = "w*"

Then you can supply the value of the variable to the cmdlet:

Get Professional Windows® PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.