Public


Definition: Declares public variables and allocates storage space. Declares, in a Classblock, a private variable.

 

Windows PowerShell enables you to create a global (public) variable simply by specifying the scope when you create the variable. For example, this command creates a variable named $ a withthe scope set to Global. Note that, when specifying a scope, you do not preface the variable name with a $; however, the variable will, in fact, be named $a.

 

$ Global :a= 199

 

Here’s an interesting use for global variables. Start up Windows PowerShell, but do notdeclare the variable $a. Instead, put the preceding line of code in a script (e.g., test.ps1), run the script, and thentype $ a fromthe command prompt. You should get back the following:

 

199

 

Because this is a global variable, it’s available in scripts, in the command shell, and in any other scope. Cool, huh?

 

Note. Admittedly, this isn’t quite the same as what the Public statement does in VBScript; that’s because the VBScript statement is concerned with classes, and we aren’t discussing Windows PowerShell classes in this introductory series. Therefore we’ve extended the definition of “public” to include Windows PowerShell scopes. That gives us a chance to talk about the Windows PowerShell global variables, which we find very cool.