Understanding Variables and Constants


Understanding the use of variables and constants in Windows PowerShell is fundamental to much of the flexibility of the PowerShell scripting language. Variables are used to hold information for use later in the script. Variables can hold any type of data, including text, numbers, and even objects.

Use of Variables

By default when working with Windows PowerShell, you do not need to declare variables before use. When you use the variable to hold data, it is declared. All variable names must be preceded with a dollar sign ($). There are a number of special variables in Windows PowerShell. These variables are created automatically and have a special meaning. A listing of the special variables and their associated meaning appears in Table 4-2.

Table 4-2: Use of Special Variables
Open table as spreadsheet

Name

Use

$^

Contains the first token of the last line input into the shell

$$

Contains the last token of the last line input into the shell

$_

The current pipeline object; used in script blocks, filters, Where-Object, ForEach-Object, and Switch

$?

Contains the success/fail status of the last statement

$Args

Used in creating functions requiring parameters

$Error

If an error occurred, the error object is saved in the $error variable.

$ExecutionContext

The execution objects available to cmdlets

$foreach

Refers to the enumerator in a foreach loop

$HOME

The user's home directory; set to %HOMEDRIVE%\%HOMEPATH%

$Input

Input is piped to a function or code block.

$Match

A hash table consisting of items found by the -match operator

$MyInvocation

Information about the currently executing script or command-line

$PSHome

The directory where PS is installed

$Host

Information about the currently executing host

$LastExitCode

The exit code of the last native application to run

$true

Boolean TRUE

$false

Boolean FALSE

$null

A null object

$this

In the Types.ps1xml file and some script block instances, this represents the current object

$OFS

Output Field Separator used when converting an array to a string

$ShellID

The identifier for the shell. This value is used by the shell to determine the ExecutionPolicy and what profiles are run at Startup

$StackTrace

Contains detailed stack trace information about the last error

In the image from book ReadUserInfoFromReg.ps1 script, there are five variables used. These are listed in Table 4-3.

Table 4-3: ReadUserInfoFromReg.ps1 Variables
Open table as spreadsheet

Name

Use

$strUserPath

Path to registry subkey "Software\Microsoft\Windows\CurrentVersion\Explorer"

$strUserName

Registry value "Logon User Name"

$strPath

Path to registry subkey "\Volatile Environment"

$strName

An array of Registry values: "LOGONSERVER", "HOMEPATH", "APPDATA", "HOMEDRIVE"

$i

Holds a single registry value name from the $strName array of registry values; $i gets assigned the value by using the ForEach alias.

The image from book ReadUserInfoFromReg.ps1 script uses the Set-Location cmdlet to change to the HKCU PSDrive. This makes it easier to work with the registry. After the location has been set to the HKCU drive, the script uses the Get-ItemProperty cmdlet to retrieve the data stored in the specified registry key. The Get-ItemProperty cmdlet needs two arguments to be supplied: path and name. The path argument receives the registry path that is stored in the $strUserPath variable, whereas the name argument receives the string stored in the $strUserName variable.

Tip 

Because the $strUserPath registry subkey was rather long, I used the grave accent (`) to continue the subkey onto the next line. In addition, because I had to close out the string with quotation marks, I used the plus symbol (+) to concatenate (glue) the two pieces of the string back together.

After the value is retrieved from the registry, the object is pipelined to the Format-List cmdlet, which once again uses the string contained in the $strUserName variable as the property to display.

Note 

The Format-List cmdlet is required in the image from book ReadUserInfoFromReg.ps1 script because of the way the Get-ItemProperty cmdlet displays the results of its operation-it returns information about the object as well as the value contained in the registry key. The use of Format-List mitigates this behavior.

The really powerful aspect of the image from book ReadUserInfoFromReg.ps1 script is that it uses the array of strings contained in the $strName variable. To read the values out of the registry, we need to “singularize” the strings contained within the $strName variable. To do this, we use the ForEach-Object cmdlet (however, we reference it by the alias foreach). After we have an individual value from the $strName array, we store the string in a variable called $i. The Get-ItemProperty cmdlet is used in exactly the same manner as it was used earlier. However, this time, we use the string contained in the $strPath variable, and the name of the registry key to read is contained in the $i variable, whose value will change four times with the execution of each pass through the array.

When the image from book ReadUserInfoFromReg.ps1 script is run, it reads five pieces of information from the registry: the logon user name, the logon server name, the user’s home path location, the user’s application data store, and the user’s home drive mapping. The image from book ReadUserInfoFromReg.ps1 script is shown here:

 ReadUserInfoFromReg.ps1 $strUserPath = "\Software\Microsoft\Windows\CurrentVersion\" `                + "Explorer" $strUserName = "Logon User Name" $strPath = "\Volatile Environment" $strName = "LOGONSERVER","HOMEPATH", "APPDATA","HOMEDRIVE" Set-Location HKCU:\    Get-ItemProperty -path $strUserPath -name $strUserName |       Format-List $strUserName foreach ($i in $strName)    {Get-ItemProperty -path $strPath -name $i |       Format-List $i}

image from book
Quick Check

Q. To read a value from the registry, which provider is used?

A. The registry provider is used to read from the registry.

Q. Which cmdlet is used to retrieve a registry key value from the registry?

A. The Get-ItemProperty cmdlet is used to retrieve a registry key value from the registry.

Q. How do you concatenate two string values?

A. You can use the plus symbol (+) to concatenate two string values together.

image from book

Exploring strings

  1. Open Windows PowerShell.

  2. Create a variable called $a and assign the value "this is the beginning" to it. The code for this is shown here:

     $a = "this is the beginning"

  3. Create a variable called $b and assign the number 22 to it. The code for this is shown here:

     $b = 22

  4. Create a variable called $c and make it equal to $a + $b. The code for this is shown here:

     $c = $a + $b

  5. Print out the value of $c. The code for this is shown here:

     $c

  6. The results of printing out c$ are shown here:

     this is the beginning22

  7. Modify the value of $a. Assign the string "this is a string" to the variable $a. This is shown here:

     $a = "this is a string"

  8. Use the up arrow and retrieve the $c = $a + $b. This command is shown here:

     $c = $a + $b

  9. Now print out the value of $c. The command to do this is shown here:

     $c

  10. Assign the string "this is a number" to the variable $b. The code to do this is shown here:

     $b = "this is a number"

  11. Use the up arrow to retrieve the $c = $a + $b command. This will cause Windows PowerShell to re-evaluate the value of $c. This command is shown here:

     $c = $a + $b

  12. Print out the value of $c. This command is shown here:

     $c

  13. Change the $b variable so that it can only contain an integer. (Data type aliases are seen in Table 4-4.) Use the $b variable to hold the number 5. This command is shown here:

     [int]$b = 5

  14. Use the up arrow to retrieve the $c = $a + $b command. This command is shown here:

     $c = $a + $b

  15. Print out the value contained in the $c variable, as shown here:

     $c

  16. Assign the string "this is a string" to the $b variable. This command is shown here:

     $b = "this is a string"

  17. Attempting to assign a string to a variable that has a [int] constraint placed on it results in the error shown here (these results are wrapped for readability):

     Cannot convert value "this is a number" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:3 + $b  <<<< = "this is a string"

  18. This concludes this procedure.

Table 4-4: Data Type Aliases
Open table as spreadsheet

Alias

Type

[int]

32-bit signed integer

[long]

64-bit signed integer

[string]

Fixed-length string of Unicode characters

[char]

A Unicode 16-bit character

[bool]

True/false value

[byte]

An 8-bit unsigned integer

[double]

Double-precision 64-bit floating point number

[decimal]

An 128-bit decimal value

[single]

Single-precision 32-bit floating point number

[array]

An array of values

[xml]

Xml objects

[hashtable]

A hashtable object (similar to a dictionary object)

These commands are found in the image from book ExploringStrings.txt script in the scripts folder for this chapter.

Use of Constants

Constants in Windows PowerShell are like variables-with two important exceptions: their value never changes, and they cannot be deleted. Constants are created by using the Set-Variable cmdlet and specifying the option argument to be equal to constant.

Note 

When referring to a constant in the body of the script, we must prefix it with the dollar sign ($), just like any other variable. However, when creating the constant (or variable for that matter) by using the Set-Variable cmdlet, when we specify the name argument, we do not use the dollar sign.

In the image from book GetHardDiskDetails.ps1 script, we create a constant called $intDriveType and assign the value of 3 to it because the WIN32_LogicalDisk WMI class uses a value of 3 in the disktype property to describe a local fixed disk. Because we are not interested in network drives, removable drives, or ram drives, we use the Where-Object to return only items that have a drivetype of 3.

image from book
Quick Check

Q. How do you create a constant in a script?

A. You create a constant in a script by using the Set-Variable and specifying the value of constant to the option argument.

Q. How do you indicate that a variable will only hold integers?

A. To indicate that a variable will only contain integers, use the [int] in front of the variable name when assigning a value to the variable.

image from book

In looking at the image from book GetHardDiskDetails.ps1 script, the value of $intDriveType is never changed. It is assigned the value of 3 on the Set-Variable line. The $intDriveType constant is only used with the Where filter line. The value of $strComputer, however, will change once for each computer name that is specified in the array $aryComputers. In this script, it will change twice. The first time through the loop, it will be equal to loopback, and the second time through the loop, it will be equal to localhost. However, if you added 250 different computer names, the effect would be the same-the value of $strComputer would change each time through the loop.

image from book GetHardDiskDetails.ps1

 $aryComputers = "loopback", "localhost" Set-Variable -name intDriveType -value 3 -option constant foreach ($strComputer in $aryComputers)    {"Hard drives on: " + $strComputer    Get-WmiObject -class win32_logicaldisk -computername $strComputer|       Where {$_.drivetype -eq $intDriveType}}




Microsoft Press - Microsoft Windows PowerShell Step by Step
MicrosoftВ® Windows PowerShell(TM) Step By Step (Step By Step (Microsoft))
ISBN: 0735623953
EAN: 2147483647
Year: 2007
Pages: 128
Authors: Ed Wilson

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net