MicrosoftВ® Windows PowerShell(TM) Step By Step (Step By Step (Microsoft))
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.
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
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
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 |
The really powerful aspect of the
When the
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}
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.
Exploring strings
-
Open Windows PowerShell.
-
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"
-
Create a variable called $b and assign the number 22 to it. The code for this is shown here:
$b = 22
-
Create a variable called $c and make it equal to $a + $b. The code for this is shown here:
$c = $a + $b
-
Print out the value of $c. The code for this is shown here:
$c
-
The results of printing out c$ are shown here:
this is the beginning22
-
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"
-
Use the up arrow and retrieve the $c = $a + $b. This command is shown here:
$c = $a + $b
-
Now print out the value of $c. The command to do this is shown here:
$c
-
Assign the string "this is a number" to the variable $b. The code to do this is shown here:
$b = "this is a number"
-
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
-
Print out the value of $c. This command is shown here:
$c
-
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
-
Use the up arrow to retrieve the $c = $a + $b command. This command is shown here:
$c = $a + $b
-
Print out the value contained in the $c variable, as shown here:
$c
-
Assign the string "this is a string" to the $b variable. This command is shown here:
$b = "this is a string"
-
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"
-
This concludes this procedure.
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
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
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.
In looking at the
$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}}
Категории