It is time to combine commands whenever a single PowerShell command can't solve your problem. One way of doing this is by using variables. PowerShell can store results of one command in a variable and then pass the variable to another command.
In addition, variables are rich 'objects' and can do much more than simply store data. In this chapter, we'll explain what variables are and how you can use them to solve complex problems.
Topics Covered:
Your Own Variables
Variables store information temporarily so you can take the information contained in a variable and process it in further steps.
$amount = 120
$VAT = 0.19
$result = $amount * $VAT
$result
22.8
$text = "Net amount $amount matches gross amount $result"
$text
Net amount 120 matches gross amount 142.8
PowerShell creates new variables automatically so there is no need to specifically "declare" variables. Simply assign data to a variable. The only thing you need to know is that variable names are always prefixed with a "$".
You can then output the variable content by entering the variable name, or you can merge the variable content into text strings. To do that, just make sure the string is delimited by double-quotes. Single-quoted text will not resolve variables.
Selecting Variable Names
In PowerShell, a variable name always begins with a dollar sign "$". The rest of the name may consist of almost anything you want: letters, numbers, and the underline character. PowerShell variable names are not case sensitive.
There is only one exception: certain special characters have special meaning for PowerShell. While you can still use those special characters in variable names, you will then need to enclose the variable name in braces. The best suggestion is not to use PowerShell's special characters in variable names to avoid braces:
${this variable name is "unusual," but permitted} = "Hello World"
${this variable name is "unusual," but permitted}
Hello World
Assigning and Returning Values
The assignment operator "=" sets a variable to a specified value. You can assign almost anything to a variable, even complete command results:
$listing = Get-ChildItem c:\
$listing
Directory: Microsoft.PowerShell.Core\FileSystem::C:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 06.26.2007 15:36 2420
d---- 05.04.2007 21:06 ATI
d---- 08.28.2006 18:22 Documents and settings
d---- 08.08.2007 21:46 EFSTMPWP
d---- 04.28.2007 02:18 perflogs
(...)
$result = ipconfig
$result
Windows IP Configuration
Ethernet adapter LAN Connection:
Media state
. . . . . . . . . . . : Medium disconnected
Connection-specific DNS Suffix:
Ethernet adapter LAN Connection 2:
Media state
. . . . . . . . . . . : Medium disconnected
Connection-specific DNS Suffix:
Wireless LAN adapter wireless network connection:
Media state
. . . . . . . . . . . : Medium disconnected
Connection-specific DNS Suffix:
Populating Several Variables with Values Simultaneously
Not only can the assignment operator assign values to a single variable, it can set the contents of several variables in one step. For example, you could set a whole series of variables to one shared initial value:
$a = $b = $c = 1
$a
1
$b
1
$c
1
Exchanging the Contents of Variables
Now and then you might want to exchange the contents of two variables. In traditional programming languages, that would require several steps:
$Value1 = 10
$Value2 = 20
$Temp = $Value1
$Value1 = $Value2
$Value2 = $Temp
With PowerShell, swapping variable content is much easier. First of all, you can write several statements in one line if you separate the statements from each other by semi-colon. Second, assignment operators will accept several variables on each side that replace each other:
$Value1 = 10; $Value2 = 20
$Value1, $Value2 = $Value2, $Value1
Assigning Different Values to Several Variables
The real trick in the last example is the comma. PowerShell always uses the comma to create a variable array (a variable that holds more than one value). We'll be exploring these arrays in depth in Chapter 4, but it is important for you to know now that the assignment operator also processes arrays. If you state to its left and right an array having the same number of elements, then it will assign the elements of the array on the right side to the elements of the array on the left side. This is a way for you to use a single assignment operator to populate different variables with different values. It can thus simplify the previous example even more:
$Value1, $Value2 = 10,20
$Value1, $Value2 = $Value2, $Value1
Overview of Variables in Use
PowerShell keeps a record of all variable assignments, which is accessible via a virtual drive called variable:. To see all currently defined variables, you should just output this drive to a list:
Dir variable:
Don't be surprised to see not only variables you've created yourself, but also many more. The reason: PowerShell also defines variables and calls them "automatic variables." You'll learn more about this soon.
Finding Variables
Using the variable: virtual drive makes it easy to find variables by allowing wildcards, just like in the file system. If you'd like to see all the variables whose name begins with the letters "value", try this:
Dir variable:value*
Name Value
---- -----
value2 20
value1 10
Dir lists the two variables $value1 and $value2 as well as returning their current contents. You can also use the Dir parameters -include and -exclude (the alias for Get-ChildItem). The next example uses the -exclude parameter to find all the variables that begin with the letters "value" but don't use an "l" in their names:
Dir variable: -include value* -exclude *1*
Name Value
---- -----
value2 20
If you'd like to know which variables currently contain the value 20, the solution isn't quite so simple, yet it is still doable. It consists of several commands piped together.
dir variable: | Out-String -stream | Select-String " 20 "
value2 20
$ 20
Here, the output from Dir is passed on to Out-String,which converts the results of Dir into text. The parameter -stream ensures that every variable supplied by Dir is separately output as text. Select-String selects the lines that include the desired value, filtering out the rest. To ensure that only the desired value is found and not other values that contain the number 20 (like 200), white space is added before and after the number 20.
Verify Whether a Variable Exists
To find out whether a variable already exists, you should again do as you would with the file system. Using the cmdlet Test-Path, you can verify whether a certain file exists. Similar to files, variables are stored in their own "drive" called variable:and every variable has a path name that you can verify with Test-Path:
Test-Path variable:\value2
True
Test-Path variable:\server
False
Whether a variable already exists or not doesn't usually matter. When you assign a value to an existing variable, the new value will simply overwrite the old one. However, sometimes you might want to assign a value only when the variable doesn't exist yet. Also, variables can be write-protected so that you cannot easily overwrite an existing variable.
Deleting Variables
Because variables are deleted automatically as soon as you exit PowerShell, you don't necessarily need to clean them up manually. If you'd like to delete a variable immediately, again, do exactly as you would in the file system:
$test = 1
Dir variable:\te*
del variable:\test
Dir variable:\te*
Using Special Variable Cmdlets
To manage your variables, PowerShell provides you with the five separate cmdlets listed in Table 3.1. You won't need these for everyday tasks because, as you've just seen, the virtual drive variable: enables you to perform the most important management tasks just as you do in the file system. Only two of the five cmdlets really offer you new options:
- New-Variable enables you to specify options, such as a description or write protection. This makes a variable into a constant. Set-Variable does the same for existing variables.
- Get-Variable enables you to retrieve the internal PowerShell variables store.
| Cmdlet |
Description |
Example |
| Clear-Variable |
Clears the contents of a variable, but not the variable itself. The subsequent value of the variable is NULL (empty). If a data or object type is specified for the variable, by using Clear-Variable the type of the objected stored in the variable will be preserved. |
Clear-Variable a same as: $a = $null |
| Get-Variable |
Gets the variable object, not the value in which the variable is stored. |
Get-Variable a |
| New-Variable |
Creates a new variable and can set special variable options. |
New-Variable value 12 |
| Remove-Variable |
Deletes the variable, and its contents, as long as the variable is not a constant or is created by the system. |
Remove-Variable a same as: del variable:\a |
| Set-Variable |
Resets the value of variable or variable options such as a description and creates a variable if it does not exist. |
Set-Variable a 12 same as: $a = 12 |
Table 3.1: Cmdlets for managing variables
Write-Protecting Variables: Creating Constants
Constants store a constant value that cannot be modified. They work like variables with a write-protection.
PowerShell doesn't distinguish between variables and constants. However, it does offer you the option of write-protecting a variable. In the following example, the write-protected variable $test is created with a fixed value of 100. In addition, a description is attached to the variable.
New-Variable test -value 100 -description `
"test variable with write-protection" -option ReadOnly
$test
100
$test = 200
The variable "test" cannot be overwritten since it is a
constant or read-only.
At line:1 char:6
+ $test <<<< = 200
The variable is now write-protected and its value may no longer be changed. You'll receive an error message if you try to change it. You must delete the variable and re-define it if you want to modify its value. Because the variable is write-protected, it behaves like a read-only file. You'll have to specify the parameter -force to delete it:
del variable:\test -force
$test = 200
A write-protected variable can still be modified by deleting it and creating a new copy of it. If you need strong protection like in traditional constants, you should create a variable with the Constant option. This will change the variable to a proper constant that may neither be modified nor deleted. Only when you quit PowerShell are constants removed. Variables with the Constant option may only be created with New-Variable. You'll get an error message if a variable already exists that has the specified name:
New-Variable test -value 100 -description `
"test variable with copy protection" -option Constant
New-Variable : A variable named "test" already exists.
At line:1 Char:13
+ New-Variable <<<< test -value 100 -description
"test variable with copy protection" -option Constant
del variable:\test -force
New-Variable test -value 100 -description `
"test variable with copy protection" `
-option Constant
del variable:\test -force
Remove-Item : variable "test" may not be removed since it is a
constant or write-protected. If the variable is write-protected,
carry out the process with the Force parameter.
At line:1 Char:4
+ del <<<< variable:\test -force
You can overwrite an existing variable by using the -force parameter of New-Variable. Of course, this is only possible if the existing variable wasn't created with the Constant option. Variables of the constant type are unchangeable once they have been created, and -force does not change this:
New-Variable test -value 100 -description "test variable" -force
New-Variable : variable "test" may not be removed since it is a
constant or write-protected.
At line:1 char:13
+ New-Variable <<<< test -value 100 -description "test variable"
$available = 123
New-Variable available -value 100 -description "test variable" -force
Variables with Description
Variables can have an optional description that helps you keep track of what the variable was intended for. However, this description appears to be invisible:
New-Variable myvariable -value 100 -description "test variable" -force
$myvariable
100
Dir variable:\myvariable
Name Value
---- -----
myvariable 100
Get-Variable myvariable
Name Value
---- -----
myvariable 100
By default, PowerShell only shows the most important properties of an object, and the description of a variable isn't one of them. If you'd like to see the description, you have to explicitly request it. You can do this by using the cmdlet Format-Table (you'll learn much about this in Chapter 5). Using Format-Table, you can specify the properties of the object that you want to see:
dir variable:\myvariable |
Format-Table Name, Value, Description -autosize
Name Value Description
---- ----- -----------
test 100 test variable
"Automatic" PowerShell Variables
PowerShell uses variables, too, for internal purposes and calls those "automatic variables." These variables are available right after you start PowerShell since PowerShell has defined them during launch. The drive variable: provides you with an overview of all variables:
Dir variable:
Name Value
---- -----
Error {}
DebugPreference SilentlyContinue
PROFILE C:\Users\Tobias Weltner\Documents\
WindowsPowerShell\Micro...
HOME C:\Users\Tobias Weltner
(...)
To understand the meaning of automatic variables, you can simply view their description:
Dir variable: | Sort-Object Name |
Format-Table Name, Description -autosize -wrap
Name Description
---- -----------
$
? Execution status of last command.
^
_
ConfirmPreference Dictates when confirmation should be requested.
Confirmation is requested when the ConfirmImpact
of the operation is equal to or greater than
$ConfirmPreference. If $ConfirmPreference is
None, actions will only be confirmed when
Confirm is specified.
ConsoleFileName Name of the current console file.
DebugPreference Dictates action taken when an Debug message is
delivered.
Error
ErrorAction Dictates action taken when an Error message is
Preference delivered.
ErrorView Dictates the view mode to use when displaying
errors.
ExecutionContext The execution objects available to cmdlets.
false Boolean False
FormatEnumeration Dictates the limit of enumeration on formatting
Limit IEnumerable objects.
HOME Folder containing the current user's profile.
Host This is a reference to the host of this
Runspace.
MaximumAliasCount The maximum number of aliases allowed in a
session.
MaximumDriveCount The maximum number of drives allowed in a
session.
MaximumErrorCount The maximum number of errors to retain in a
session.
MaximumFunctionCount The maximum number of functions allowed in a
session.
MaximumHistoryCount The maximum number of history objects to retain
in a session.
MaximumVariableCount The maximum number of variables allowed in a
session.
MyInvocation
NestedPromptLevel Dictates what type of prompt should be
displayed for the current nesting level.
null References to the null variable always return
the null value. Assignments have no effect.
OutputEncoding The text encoding used when piping text to a
native executable.
PID Current process ID.
PROFILE
ProgressPreference Dictates action taken when Progress Records
are delivered.
PSHOME Parent folder of the host application of this
Runspace.
PWD
ReportErrorShow Causes errors to be displayed with a description
ExceptionClass of the error class.
ReportErrorShow Causes errors to be displayed with the inner
InnerException exceptions.
ReportErrorShow Causes errors to be displayed with the source of
Source the error.
ReportErrorShow Causes errors to be displayed with a stack
trace.
StackTrace
ShellId The ShellID identifies the current shell. This
is used by #Requires.
StackTrace
true Boolean True
VerbosePreference Dictates the action taken when a Verbose message
is delivered.
WarningPreference Dictates the action taken when a Warning message
is delivered.
WhatIfPreference If true, WhatIf is considered to be enabled for
all commands.
Most automatic variables are very well documented. Variables are assigned to three categories:
- User information: PowerShell permanently stores some important information. For example, the path name of the standard profile in $HOME. In addition, some standard variables, like $true and $false, are set.
- Fine adjustments: Numerous default settings allow the behavior of PowerShell to be modified and customized. For example, you can set how detailed error messages are reported, or whether a command should continue to execute, in the event of an error. You'll learn more about this in Chapter 11.
- Running time information: PowerShell returns valuable information when it executes statements. For example, a function can determine who calls it, or a script can determine the location of its folder.
In other respects, automatic variables are no different from the variables you define yourself as you can read the contents and use them in much the same way:
$HOME
C:\Users\UserA
"current process -ID of PowerShell is $PID"
current process -ID of PowerShell is 6116
Get-Process -id $PID
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
656 22 107620 72344 334 118,69 6116 PowerShell
notepad $profile
To find out more, use Get-Help:
Get-Help about_Automatic_variables
PowerShell write protects several of its automatic variables. While you can read them, you can't modify them. That makes sense because information, like the process-ID of the PowerShell console or the root directory, should not be modified.
$pid = 12
Cannot overwrite variable "PID" because it is read-only or constant.
At line:1 char:5
+ $pid <<<< = 12
A little later in this chapter, you'll find out more about how write-protection works. You'll then be able to turn write-protection off and on for variables that already exist. However, you should never do this for automatic variables because that can cause the PowerShell console to crash. One reason is because PowerShell continually modifies some variables. If you set them to read-only, PowerShell may stop and not respond to any inputs.
Environment Variables
Older consoles do not typically have a variable system of their own that was as sophisticated as PowerShell's. Instead, those consoles relied on "environment variables," which are managed by Windows itself. Environment variables are important sources of information for PowerShell because they include many details about the operating system. Moreover, while PowerShell's variable are visible only inside of the current PowerShell session, environment variables can persist and thus can be readable by other programs.
Working with environment variables in PowerShell is just as easy as working with internal PowerShell variables. All you have to do is to tell PowerShell precisely which variable you mean. To do this, you should specify the variable source at the beginning of the variable name. For environment variables, it's env:.
Reading Particular Environment Variables
You can read the location of the Windows folder of the current computer from a Windows environment variable:
$env:windir
C:\Windows
By adding env:, you've instructed PowerShell not to look for the variable windir in the normal PowerShell variable store, but in Windows environment variables. In other respects, the variable behaves just like any other PowerShell variable. For example, you could embed it in the text:
"The Windows folder is here: $env:windir"
The Windows folder is here: C:\Windows
You can just as easily use the variable with commands and switch over temporarily to the Windows folder in the following way:
Push-Location
cd $env:windir
Dir
Pop-Location
Searching for Environment Variables
PowerShell keeps track of Windows environment variables and lists them in the env: virtual drive. So, if you'd like an overview of all existing environment variables, you should just list the contents of the env: drive:
Dir env:
Name Value
---- -----
Path C:\Windows\system32;C:\Windows;C:\Windows\System32
\Wbem;C:\
TEMP C:\Users\TOBIAS~1\AppData\Local\Temp
ProgramData C:\ProgramData
PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;
.MSC;.4mm
ALLUSERSPROFILE C:\ProgramData
PUBLIC C:\Users\Public
OS Windows_NT
USERPROFILE C:\Users\Tobias Weltner
HOMEDRIVE C:
(...)
You'll be able to retrieve the information it contains when you've located the appropriate environment variable and you know its name:
$env:userprofile
C:\Users\Tobias Weltner
Creating New Environment Variables
You can create completely new environment variables in the same way you create normal variables. Just specify in which area the variable is to be created, with env:
$env:TestVar = 12
Dir env:\t*
Name Value
---- -----
TMP C:\Users\TOBIAS~1\AppData\Local\Temp
TEMP C:\Users\TOBIAS~1\AppData\Local\Temp
TestVar 12
Deleting and Modifying Environment Variables
Deleting and modifying environment variables are done in the same way as normal PowerShell variables. For example, if you'd like to remove the environment variable windir, just delete it from the env:drive:
del env:\windir
$env:windir
You can modify environment variables by simply assigning new variables to them. The next line will turn your system into an Apple computer—at least to all appearances:
$env:OS = "Apple MacIntosh OS X"
Dir env:
Name Value
---- -----
Path C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\
(...)
OS Apple MacIntosh OS X
USERPROFILE C:\Users\Tobias Weltner
HOMEDRIVE C:
Aren't these changes dangerous? After all, the environment variables control the entire system. Fortunately, all changes you make are completely safe and reversible. PowerShell works with a copy of real environment variables, the so called "process" set. After closing and restarting PowerShell, the environment variables will return to their previous state. Your changes only affect the current PowerShell session. Use direct .NET framework methods to change environment variables persistently. We cover those in a moment.
You can add new folders to the list of trustworthy folders by changing or appending environment variables. You have read in Chapter 2 that content in trustworthy folders (documents, scripts, programs) can be launched in PowerShell without having to specify an absolute or relative path name or even a file extension.
md c:\myTools
" 'Hello!' " > c:\myTools\sayHello.ps1
C:\myTools\sayHello.ps1
Hello!
$env:path += ";C:\myTools"
sayHello
Hello!
Permanent Modifications of Environment Variables
All changes to environment variables only affect the local copy that your PowerShell session is using. To make changes permanent, you have two choices. You can either make the changes in one of your profile scripts, which get executed each time you launch PowerShell or you can use sophisticated .NET methods directly to change the underlying original environment variables. When you do this your changes are permanent.
$oldValue = [environment]::GetEnvironmentvariable("Path", "User")
$newValue = ";c:\myTools"
[environment]::SetEnvironmentvariable("Path", $newValue, "User")
Access to commands of the .NET Framework as shown in this example will be described in depth in Chapter 6.
When you close and restart PowerShell, the Path environment variable will now retain the changed value. You can easily check this:
$env:Path
The permanent change you just made applies only to you, the logged-on user. If you'd like the change to be in effect for all computer users, replace the "User" argument by "Machine." You will need full administrator privileges to do that.
Change environment variables permanently only when there is no other way. For most purposes, it is completely sufficient to change the temporary process set from within PowerShell.
Drive Variables
When you access variables outside of PowerShell's own variable system (like the environment variables), the prefix to the variable name really is just the name of the virtual drive that gives access to the information. Let's take a closer look:
$env:windir
Using this statement, you've just read the contents of the environment variable windir. However, in reality, env:windir is a file path and leads to the "file" windir on the env:drive. So, if you specify a path name behind "$", this variable will furnish the contents of the specified "file".
Directly Accessing File Paths
This actually works with (nearly) all drives, even with real data drives. In this case, the direct variable returns the contents of the actual file. The path must be enclosed in braces because normal files paths include special characters like ":" and "\", which PowerShell can misinterpret:
${c:\autoexec.bat}
REM Dummy file for NTVDM
And there's yet another restriction: the path behind "$" is always interpreted literally. You cannot use variables or environment variables in it. As a result, the following command would be useless because PowerShell wouldn't find the file:
${$env:windir\windowsupdate.log}
This problem could be solved by the cmdlet Invoke-Expression. It executes any kind of command that you pass as a string. Here, you could assemble the path name and pass it to Invoke-Expression:
$command = "`${$env:windir\windowsupdate.log}"
Invoke-Expression $command
The "`" character in front of the first "$", by the way, is not a typo but a character as it's known as the "backtick" character. You specify it in front of all characters that normally have a special meaning that you want to override during the current operation. Without the backtick character, PowerShell would interpret the contents in the first line as a direct variable and replace it with the value of the variable. But after a backtick, the "$" character remains a normal text character.
Why didn't we enclose the text in the first line in simple quotation marks? Because then PowerShell wouldn't have made any automatic replacements. The environment variable $env:windir wouldn't have been resolved, either. Consequently, you need the backtick character in text whenever you want to resolve only part of the text.
Direct variables work with most (but not all) drives that Get-PSDrive reports. For example, you would address the function with your path name to see the definition of a function:
$function:tabexpansion
You can also load functions in Notepad in this way:
$function:tabexpansion > function.ps1; notepad function.ps1
| Area allocator |
Description |
| env: |
Environment variables |
| function: |
Functions |
| variable: |
Variables |
| [Path name] |
File system |
Table 3.2: Variable areas made available by external providers
Ad-hoc Variables: Sub-Expressions
There are also variables that are never assigned a value in the first place. Instead, the variable contains an expression. The expression is evaluated and yields the result each time you query the variable. The code in the parentheses always recalculates the content of this "variable."
$(2+2)
4
Why not just simply write:
(2+2)
4
Or even simpler:
2+2
4
$(2+2) is a variable and, consequently, like all other variables, can be embedded. For example, in text:
"Result = $(2+2)"
Result = 4
You'll find that ad hoc variables are important once you're working with objects and want to output a particular object property. We'll discuss objects in more detail later in Chapter 6. Until then, the following example should make the principle clear:
$file = Dir c:\autoexec.bat
$file.length
"The size of the file is $($file.Length) bytes."
Try this without ad hoc variables. PowerShell would only have replaced $file with the value of the variable and appended ".Length" as static text:
"The size of the file is $($file.Length) bytes."
The size of the file is
C:\autoexec.bat.Length bytes.
Scope of Variables
PowerShell variables can have a "scope" which determines where a variable is available. PowerShell supports four special variable scopes: global, local, private, and script. These scopes allow you to restrict variable visibility in functions or scripts.
Automatic Restriction
If you don't do anything at all, PowerShell will automatically restrict the visibility of its variables. To see how this works, create a little test script:
Notepad test1.ps1
Notepad will open. Type the following script, save it, and then close Notepad:
$windows = $env:windir
"Windows Folder: $windows"
Now call your script:
.\test.ps1
If your script doesn't start, script execution may be turned off. By entering the command Set-ExecutionPolicy RemoteSigned, you can grant PowerShell permission to run scripts. You'll learn more about this in Chapter 10.
The script reports the Windows folder. From within the script, the folder path is stored in the variable $windows. After the script has done its work, take a look to see what variables the script has left behind: retrieve the variable $windows. It's empty. The variables in your script were defined in a different scope than the variables within your console and so were isolated from each other. $windows in the console and $windows in your script are, in fact, completely different variables as shown by this script:
$windows = "Hello"
.\test1.ps1
$windows
"Hello"
Although the script in its variable $windows stored other information, the variable $windows in your console retains its value. PowerShell normally creates its own variable scope for every script and every function.
Changing Variable Visibility
You can easily find out how the result would have looked without automatic restrictions on variable visibility. All you do is type a single dot "." before the script file path to turn off restrictions on visibility. Type a dot and a space in front of the script:
$windows = "Hello"
. .\test1.ps1
$windows
"C:\Windows"
This time, the variables within the script will take effect on variables in the console. If you launch the script "dot-sourced," PowerShell won't create new variables for your script. Instead, it uses the variable scope of the caller. That has advantages and disadvantages that you'll have to weigh carefully in each application.
Advantage of Lifting Visibility Restrictions: Clear and Unambiguous Start Conditions
Imagine an example in which a script creates a read-only variable as a constant. Such variables may neither be modified nor removed. This won't be a problem if you start the script with scoping restrictions because the constant is created in the variable scope of the script. The entire variable scope will be completely disposed of when the script ends. Constants that you create in scripts are therefore write-protected only within the script. You can create another test script to verify that:
Notepad test2.ps1
Type in it the following code, which creates a read-only constant:
New-Variable a -value 1 -option Constant
"Value: $a"
Save the test script and close Notepad. The write-protected constant will be created when you start the script the way you would normally, , but it will also be removed when the script ends. You can run the script as often as you wish:
.\test2.ps1
Value: 1
.\test2.ps1
Value: 1
Now try to call the "dot-sourced" script. Because it doesn't include any scoping restrictions anymore, the constant will not be created in the variable scope of the script, but in the variable scope of the caller, i.e., the console. The constant will be preserved when the script ends. If you call the script a second time, it will fail because it can't overwrite the constant that still exists from the script that was last invoked:
. .\test2.ps1
Value: 1
. .\test2.ps1
New-Variable : A variable with the name "a" already exists.
At C:\Users\Tobias Weltner\test2.ps1:1 char:13
+ New-Variable <<<< a -value 1 -option Constant
It's interesting that you can still always run the script, despite the existing variable $a, if you start it again normally and with its own variable scope:
.\test2.ps1
Value: 1
The script now takes all variables from the caller's variable scope, and so the existing variable $a as well, but when new variables are created or existing ones modified, this happens exclusively in the script's own variable scope. Therefore, conflicts are minimized when scoping restriction is active.
This works conversely, too: use the AllScope option if you'd like to expressly prevent the own variable scope from redefining a variable from another variable scope. This way, the variable will be copied automatically to every new variable scope and created there as a local variable. This enables you to prevent constants from being re-defined in another variable scope:
Function Test {$setValue = 99; $setValue }
New-Variable setValue -option "ReadOnly" -value 200
Test
99
Remove-Variable setValue -force
New-Variable setValue -option "ReadOnly,<b>AllScope</b>" -value 200
The variable "setValue" cannot be overwritten since it is a
constant or read-only.
At line:1 char:27
+ Function Test {$setValue <<<< = 99; $setValue }
200
Setting the Scope of Individual Variables
Up to now, the governing principle was "all or nothing": either all variables of a function or a script were private or they were public (global). Now, let's use the scope modifiers private, local, script, and global.
| Scope allocation |
Description |
| $private:test = 1 |
The variable will be created only in the current scope and not passed to other scopes. Consequently, it can only be read and written in the current scope. |
| $local:test = 1 |
Variables will be created only in the local scope. That is the default for variables that are specified without a scope. Local variables can be read from scopes originating from the current scope, but they cannot be modified. |
| $script:test = 1 |
The variable is valid only in a script, but valid everywhere in it. Consequently, a function in a script can address other variables, which, while defined in a script, are outside the function. |
| $global:test = 1 |
The variable is valid everywhere, even outside functions and scripts. |
Table 3.3: Variable scopes and validity of variables
PowerShell automatically creates scopes, even when you first start the PowerShell console. It gets the first (global) scope. Additional scopes will be added when you use functions and scripts. Every function and every script acquires its own scope. As long as you work from within the PowerShell console, there will be only one scope. In this case, all scope allocations will function in exactly the same way:
$test = 1
$local:test
1
$script:test = 12
$global:test
12
$private:test
12
Create a second scope by defining a function. As soon as you call the function, PowerShell will switch to the function's own new scope. And now things appear somewhat confusing: which rules apply to variables and their validity? Let's take a look at what happens to variables that you create in the scope of the console and then read or modify in the scope of the function:
Function test { "variable = $a"; $a = 1000 }
$a = 12
Test
variable = 12
$a
12
When you don't use any special scope allocators, a new scope can read the variables of the old scope, but not change them. If the new scope modifies a variable from the old scope, as in the example above, then the modification will be automatically created in a new local variable of the new scope. The modification has no effect on the old scope.
Is it possible to prevent variables from the old scope from being read by a new scope? The answer is yes. Variables are private for the allocator, since the variables that you create with it are not passed to other scopes. The function then reports "variable = ", because the variable $a is suddenly invisible to the function.
Function test { "variable = $a"; $a = 1000 }
$private:a = 12
Test
variable =
$a
12
Only when you create a completely new variable by using $private: is it in fact private. If the variable already existed, PowerShell will not reset the scope of the existing variable. That is (somewhat) logical, because there is only one scope in the console scope. The existing variable is found under the private: allocator and so is not created again.
To achieve the result you expect, you must either first remove the existing variable $a using the statement Remove-Variable a before you create it again, or manually allocate the status of a private variable to an existing variable: (Get-Variable a).Options = "Private". Also, by using (Get-Variable a).Options = "None" you can make a variable become a local variable again. The scope of a variable is disclosed, as shown in Table 3.6, by selecting the Options property.
It works conversely too as the function can also modify the variable in the console scope. That's the purpose of the global: allocator. If it's specified, then the statement changes the variable in all existing scopes:
Function test { "variable = $a"; $global:a = 1000 }
Remove-Variable a
$private:a = 12
Test
variable =
$a
1000
The allocator script: works in a very similar way. It makes a variable global inside of a script, but does not touch variables outside of the script. If you call the function directly from within the console, then global: and script: will supply the same result. But when you use script: from within PowerShell scripts, you will create variables that are valid everywhere within the script. However, after termination of the script, will have no effect on the console used to call the script.
| Scope |
Use |
| $global |
The variable is valid in all scopes and is preserved when a script or a function ends its work. |
| $script |
The variable is valid only within a script, but everywhere within it. Once the script is executed, the variable is removed. |
| $private |
The variable is valid only in the current scope, either a script or a function. It cannot be passed to other scopes. |
| $local |
The variable is valid only in the current scope. All scopes called with it can read, but not change, the contents of the variable. Modifications are also stored in new local variables of the current scope. $local: is the default if you don't specify a particular scope. |
Table 3.4: Practical usage of scope allocations
Variable Types and "Strongly Typing"
Variables store arbitrary information when PowerShell automatically picks the appropriate data type. You don't have to do anything. However, by appending the command .GetType().Name to a variable, you can verify the data type that PowerShell has chosen for a variable. You don't even need the variable. Type the value in parentheses and call .GetType().Name to find out in which data type PowerShell stores the value:
(12).GetType().Name
Int32
(1000000000000).GetType().Name
Int64
(12.5).GetType().Name
Double
(12d).GetType().Name
Decimal
("H").GetType().Name
String
(Get-Date).GetType().Name
DateTime
PowerShell assigns the best-fit primitive data type for a given value. If a number is too large for a 32-bit integer, it will use a 64-bit integer. If it's a decimal number, then the Double data type will be used. In the case of text, PowerShell uses the String data type. Date and time values are stored in DateTime objects.
This process of automatic selection is called "weakly typed," and while easy, it's also often restrictive—or even risky. If PowerShell picks the wrong data type, strange things can happen. For example, let's say a variable should really store the number of files to be copied. If you erroneously assign a text value instead of a numeric value to this variable, PowerShell will happily store the text, not the number. The variable type will be automatically modified. This is why professional programmers and script developers often prefer strongly typed variables that specify the exact type of data to be stored, rather than delivering error messages when a wrong data type is assigned.
Another reason for a strong type specification: Every data type has its own set of helper functions. In fact, PowerShell doesn't always select the best data type for a particular value. For example, date, time and XML, are by default stored as plain text in a String data type. This is somewhat unfortunate, because you'll have to do without many useful date or XML commands that use specialized DateTime or XML data types. So, in practice, there are two important reasons for you to set the variable type yourself:
- Type safety: If you have assigned a type to a variable yourself, then the type will be preserved no matter what happens and will never be automatically modified. You can be absolutely sure that a value of the correct type is stored in the variable. If later on someone were to mistakenly assign a value to the variable that doesn't match the originally chosen type, this will cause an error message to be delivered.
- Special variable types: When automatically assigning a variable type, PowerShell takes into consideration only general variable types like Int32 or String. Often, it's appropriate to store values in a specialized variable type like DateTime in order to be able to use the special commands and options available for this variable type.
Assigning Fixed Types
To assign a particular type to a variable, enclose it in square brackets before the variable name. For example, if you know that a particular variable should hold only numbers in the range 0 to 255, you could create this variable explicitly with the Byte type:
[Byte]$flag = 12
$flag.GetType().Name
Byte
The variable will now store your contents in a single byte, which is not only very economical, but it will also flag it with an error if a value outside the permissible range is specified:
$flag = 300
The value "300" cannot be converted to the type "System.Byte".
Error: "The value for an unsigned byte was too large or too small."
At line:1 char:6
+ $flag <<<< = 300
The Advantages of Specialized Types
There is an additional and important reason to assign data types manually because every data type has its own set of special commands. For example, a date can be stored as text in a String data type. And that's just exactly what PowerShell does: it's not clever enough to automatically guess that this really is a date or time:
$date = "November 12, 2004"
$date
November 12, 2004
If you store a date as String, then you'll have no access to special date functions. Only DateTime objects make them available. So, if you're working with date and time indicators, it's better to store them explicitly as DateTime:
[datetime]$date = "November 12, 2004"
$date
Friday, November 12, 2004 00:00:00
The output of the variable will now immediately tell you the day of the week corresponding to the date, and also enable comprehensive date and time calculation commands. That makes it easy, for example, to find the date 60 days later:
$date.AddDays(60)
Tuesday, January 11, 2005 00:00:00
PowerShell supports all the usual .NET variable types that you find in Table 3.5. XML documents can be much better processed using the XML data type then the standard String data type:
$t = "<servers><server name='PC1' ip='10.10.10.10'/>" +
"<server name='PC2' ip='10.10.10.12'/></servers>"
$t
<servers><server name='PC1' ip='10.10.10.10'/>
<server name='PC2' ip='10.10.10.12'/></servers>
[xml]$list = $t
$list.servers
server
------
{PC1, PC2}
$list.servers.server
name ip
---- --
PC1 10.10.10.10
PC2 10.10.10.12
$list.servers.server[0].ip = "10.10.10.11"
$list.servers
name ip
---- --
PC1 10.10.10.11
PC2 10.10.10.12
$list.get_InnerXML()
<servers><server name="PC1" ip="10.10.10.11" />
<server name="PC2" ip="10.10.10.12" /></servers>
| Variable type |
Description |
Example |
| [array] |
An array |
|
| [bool] |
Yes-no value |
[boolean]$flag = $true |
| [byte] |
Unsigned 8-bit integer, 0...255 |
[byte]$value = 12 |
| [char] |
Individual unicode character |
[char]$a = "t" |
| [datetime] |
Date and time indications |
[datetime]$date = "12.Nov 2004 12:30" |
| [decimal] |
Decimal number |
[decimal]$a = 12 $a = 12d |
| [double] |
Double-precision floating point decimal |
$amount = 12.45 |
| [guid] |
Globally unambiguous 32-byte identification number |
[guid]$id = [System.Guid]::NewGuid() $id.toString() |
| [hashtable] |
Hash table |
|
| [int16] |
16-bit integer with characters |
[int16]$value = 1000 |
| [int32], [int] |
32-bit integers with characters |
[int32]$value = 5000 |
| [int64], [long] |
64-bit integers with characters |
[int64]$value = 4GB |
| [nullable] |
Widens another data type to include the ability to contain null values. It can be used, among others, to implement optional parameters |
[Nullable``1[[System.DateTime]]]$test = Get-Date $test = $null |
| [psobject] |
PowerShell object |
|
| [regex] |
Regular expression |
$text = "Hello World" [regex]::split($text, "lo") |
| [sbyte] |
8-bit integers with characters |
[sbyte]$value = -12 |
| [scriptblock] |
PowerShell scriptblock |
|
| [single], [float] |
Single-precision floating point number |
[single]$amount = 44.67 |
| [string] |
String |
[string]$text = "Hello" |
| [switch] |
PowerShell switch parameter |
|
| [timespan] |
Time interval |
[timespan]$t = New-TimeSpan $(Get-Date) "1.Sep 07" |
| [type] |
Type |
|
| [uint16] |
Unsigned 16-bit integer |
[uint16]$value = 1000 |
| [uint32] |
Unsigned 32-bit integer |
[uint32]$value = 5000 |
| [uint64] |
Unsigned 64-bit integer |
[uint64]$value = 4GB |
| [xml] |
XML document |
|
Table 3.5: Variable types
Variable Management: Behind the Scenes
Whenever you create a new variable in PowerShell, it will be stored "behind the scenes" in a PSVariable object. This object contains not just the value of the variable, but also other information, such as the description that you assigned to the variable or additional options like write-protection.
If you retrieve a variable in PowerShell, PowerShell will return only the variable value. If you'd like to see the remaining information that was assigned to the variable, you'll need the underlying PSVariable object. Get-Variable will get it to you:
$testvariable = "Hello"
$psvariable = Get-Variable testvariable
You can now display all the information about $testvariable by outputting $psvariable. To see all object properties and not just the default properties, pipe the output to the cmdlet Format-List:
$psvariable | Format-List
Name : testvariable
Description :
Value : Hello
Options : None
Attributes : {}
- Description: The description you specified for the variable.
- Value: the value assigned currently to the variable (i.e. its contents).
- Options: Options that have been set such as write-protection or AllScope.
- Attributes: Additional features, such as permitted data type of a variable for strongly typed variables. The brackets behind Attributes indicate that this is an array, which can consist of several values that can be combined with each other.
Subsequent Modification of Variables Options
One reason for dealing with the PSVariable object of a variable is to modify the variable's settings. Use either the cmdlet Set-Variable or directly modify the PSVariable object. For example, if you'd like to change the description of a variable, get the appropriate PSVariable object and modify its Description property:
$test = "New variable"
$psvariable = Get-Variable test
$psvariable.Description = "Subsequently added description"
Dir variable:\test | Format-Table name, description
Name Description
---- -----------
test Subsequently added description
(Get-Variable test).Description =
"An additional modification of the description."
Dir variable:\test | Format-Table name, description
Name Description
---- -----------
test An additional modification of the description.
Set-Variable test -description "Another modification"
Dir variable:\test | Format-Table name, description
Name Description
---- -----------
test Another modification
As you can see in the example above, you do not need to store the PSVariable object in its own variable to access its Description property. Instead, use a sub-expression, i.e. a statement in parentheses. PowerShell will then evaluate the contents of the sub-expression separately. The expression directly returns the required PSVariable object so you can then call the Description property directly from the result of the sub-expression. You could have done the same thing by using Set-Variable. Reading the settings works only with the PSVariable object:
(Get-Variable test).Description
An additional modification of the description.
Activating Write-Protection
You can manipulate other variable properties, too. For example, if you'd like to write-protect a variable, do this:
$Example = 10
(Get-Variable Example).Options = "ReadOnly"
Set-Variable Example -option "None" -force
$Example = 20
The Constant option must be set when a variable is created because you may not convert an existing variable into a constant.
$constant = 12345
(Get-Variable constant).Options = "Constant"
Exception in setting "Options": "The existing variable "constant"
may not be set as a constant. Variables may only be set as
constants when they are created."
At line:1 char:26
+ (Get-Variable constant).O <<<< options = "Constant"
The remaining two options, Private and AllScope, are the basis for local and global variables as they can then be extracted using the method described above.
| Option |
Description |
| "None" |
NO option (default) |
| "ReadOnly" |
Variable contents may only be modified by means of the -force parameter |
| "Constant" |
Variable contents can't be modified at all. This option must already be specified when the variable is created. Once specified this option cannot be changed. |
| "Private" |
The variable is visible only in a particular context (local variable). |
| "AllScope" |
The variable is automatically copied in a new variable scope. |
Table 3.6: Options of a PowerShell variable
Type Specification of Variables
PowerShell stores the strict data type of a variable in the Attributes property if you specified a special type. As long as Attributes is empty, the variable will store any type of data and PowerShell will automatically select the appropriate data type.
Once you assign a fixed data type to a variable, the data type will be stored in the Attributes property, setting the variable to the assigned data type. If you delete the Attributes property, the variable will be un-typed again and stores all kinds of data:
(Get-Variable a).Attributes
TypeId
------
System.Management.Automation.ArgumentTypeConverterAttribute
(Get-Variable a).Attributes.Clear()
$a = "Test"
Verifying and Validating Variable Contents
The Attributes property of a PSVariable object can include additional conditions, such as the maximum length of a variable. In the following example, a valid length from 2 to 8 characters is assigned to a variable. An error will be generated if you try to store text that is shorter than 2 characters or longer than 8 characters:
$a = "Hello"
$aa = Get-Variable a
$aa.Attributes.Add($(New-Object `
System.Management.Automation.ValidateLengthAttribute `
-argumentList 2,8))
$a = "Permitted"
$a = "Prohibited because its length is not from 2 to 8 characters"
Because of an invalid value verification (Prohibited because
its length is not from 2 to 8 characters) may not be carried out for
the variable "a".
At line:1 char:3
+ $a <<<< = "Prohibited because its length is not from 2 to 8
In the above example Add() added a new .NET object to the attributes with New-Object. You'll learn more about New-Object in Chapter 6. Along with ValidateLengthAttribute, there are additional restrictions that you can place on variables.
| Restriction |
Category |
| Variable may not be zero |
ValidateNotNullAttribute |
| Variable may not be zero or empty |
ValidateNotNullOrEmptyAttribute |
| Variable must match a Regular Expression |
ValidatePatternAttribute |
| Variable must match a particular number range |
ValidateRangeAttribute |
| Variable may have only a particular set value |
ValidateSetAttribute |
Table 3.7: Available variable validation classes
In the following example, the variable must contain a valid e-mail address or all values not matching an e-mail address will generate an error. The e-mail address is defined by what is called a Regular Expression. You'll learn more about Regular Expressions in Chapter 13.
$email = "tobias.weltner@powershell.com"
$v = Get-Variable email
$pattern = "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b"
$v.Attributes.Add($(New-Object `
System.Management.Automation.ValidatePatternAttribute `
-argumentList $pattern))
$email = "valid@email.de"
$email = "invalid@email"
Because of an invalid value verification (invalid@email) may not
be carried out for the variable "email".
At line:1 char:7
+ $email <<<< = "invalid@email"
If you want to assign a set number range to a variable, use ValidateRangeAttribute. The variable $age accepts only numbers from 5 to 100:
$age = 18
$v = Get-Variable age
$v.Attributes.Add($(New-Object `
System.Management.Automation.ValidateRangeAttribute `
-argumentList 5,100))
$age = 30
$age = 110
Because of an invalid value verification (110) may not be
carried out for the variable "age".
At line:1 char:7
+ $age <<<< = 110
If you would like to limit a variable to special key values, ValidateSetAttribute is the right option. The variable $option accepts only the contents yes, no, or perhaps:
$option = "yes"
$v = Get-Variable option
$v.Attributes.Add($(New-Object `
System.Management.Automation.ValidateSetAttribute `
-argumentList "yes", "no", "perhaps"))
$option = "no"
$option = "perhaps"
$option = "don't know"
Verification cannot be performed because of an invalid value
(don't know) for the variable "option".
At line:1 char:8
+ $option <<<< = "don't know"
The validations that you applied to variables in the above example were originally designed for cmdlets, but you can also use them for variables as well.
If you'd like to find out more about the parameters that a cmdlet accepts, you should simply examine the attribute of the cmdlet parameter and look for validation entries. The following example examines all parameters of the Get-ChildItem cmdlet and takes a closer look at the range of permitted values of the -OutBuffer parameter:
(Get-Command Get-ChildItem).ParameterSets
(...)
(Get-Command Get-ChildItem).ParameterSets |
ForEach-Object { $_.Name }
Items
LiteralItems
(Get-Command Get-ChildItem).ParameterSets |
ForEach-Object { $_.Parameters } | ForEach-Object { $_.Name }
$parameter = (Get-Command Get-ChildItem).ParameterSets |
ForEach-Object { $_.Parameters } |
Where-Object { $_.Name -eq "OutBuffer" } |
Select-Object -first 1
$parameter
Name : OutBuffer
ParameterType : System.Int32
IsMandatory : False
IsDynamic : False
Position : -2147483648
ValueFromPipeline : False
ValueFromPipelineByPropertyName : False
ValueFromRemainingArguments : False
HelpMessage :
Aliases : {ob}
Attributes : {System.Management.Automation.
AliasAttribute, __AllParameter
Sets,System.Management.Automat
ion.ValidateRangeAttribute}
$parameter.Attributes |
Where-Object { $_.TypeId -match "ValidateRangeAttribute" }
MinRange MaxRange TypeId
-------- -------- ------
0 2147483647 System.Management.Automat...
Summary
Variables store any information. The variable name always begins with the dollar sign "$". The variable name can consist of numbers, characters, and special characters like the underline character "_". Variables are not case-sensitive. If you'd like to use characters in variable names with special meaning to PowerShell (like parenthesis), the variable name must be enclosed in braces. PowerShell doesn't require that variables be specifically created or declared before use.
Aside from the variables that you create yourself, there are predefined variables that PowerShell creates called "automatic variables." These variables function like self-defined variables, but they already include useful key system data or configuration data for PowerShell.
PowerShell always stores variables internally in a PSVariable object. For example, it contains settings that write-protect a variable or attach a description to it (Table 3.6). It's easiest for you to activate this special function by using the New-Variable or Set-Variable cmdlets (Table 3.1).
By default, variables store any values you want. PowerShell automatically ensures that the variable type matches the value. If you'd like to set variables to a particular variable type ("strong type specification"), specify the desired type (Table 3.5) in square brackets before the variable name. Then the variable will store only the values that match the type. In addition, the variable will now enable the special commands associated with the variable type, such as date manipulation and math with the DateTime variable type.
Every variable is created in a fixed scope, which PowerShell uses to determine the valid scope of a variable. When PowerShell starts, an initial variable scope is created, and every script and every function receive their own respective scope. You may specify a special scope by typing the name of the desired scope before the variable name and separating it with a colon from the variable name.
You can use the local:, private:, script:, and global: scopes, to address local and global variables. In addition, further providers can make their own scopes available, which enable you to address their information just like normal variables. For example, environment variables, which can be accessed through env: (Table 3.2).
Finally, direct variables are special variable types. Variable names determine their values. Either a valid file path is specified as a valid file path, and the variable outputs the contents of this data object, or the variable name consists of PowerShell code in parentheses. PowerShell then recalculates the respective "contents" of the variable.
Posted
Oct 22 2008, 04:25 AM
by
ps1