设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

BCM 门户 IT世界 资料备录 查看内容

Varibles in PowerShell

2011-11-22 10:07| 发布者: Test| 查看: 364| 评论: 0|来自: PowerShell.com

摘要: 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 ...

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.

# Create variables and assign to values
$amount = 120
$VAT = 0.19

# Calculate:
$result = $amount * $VAT

# Output result
$result
22.8
# Replace variables in text with values:
$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:

# Variable names with special characters belong in 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:

# Temporarily store results of a cmdlet:
$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
(...)
# Temporarily store the result of a legacy external command:
$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:

# Populate several variables with the same value in one step:
$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:

# Exchange variable values:
$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:

# Populate several variables with the same value in one step:
$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:

# Verify whether the variable $value2 exists:
Test-Path variable:\value2
True
# verify whether the variable $server exists:
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:

# create a test variable:
$test = 1


# verify that the variable exists:
Dir variable:\te*


# delete variable:
del variable:\test


# variable is removed from the listing:
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:

  1. 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.
  2. 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.

# Create new variable with description and write-protection:
New-Variable test -value 100 -description `
"test variable with write-protection" -option ReadOnly
$test
100
# Variable contents cannot be modified:
$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 cannot write over existing variables:
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
# If existing variable is deleted, New-Variable can create
# a new one with the "Constant" option:
del variable:\test -force
New-Variable test -value 100 -description `
"test variable with copy protection" `
-option Constant

# variables with the "Constant" option may neither be
# modified nor deleted:
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:

# Parameter -force overwrites existing variables if these do not
# use the "Constant" option:
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"
# normal variables may be overwritten with -force without difficulty.
$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:

# Create variable with description:
New-Variable myvariable -value 100 -description "test variable" -force

# Variable returns only the value:
$myvariable
100
# Dir and Get-Variable also do not deliver the description:
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:

# variable contains a description:
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:

# Verify user profile:
$HOME
C:\Users\UserA
# Verify PowerShell Process -id and access profile:
"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
# Open the standard user profile in notepad for editing:
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:

# save in current folder:
Push-Location

# change to Windows folder
cd $env:windir
Dir

# change back to initial location after executed task
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:

# Environment variable will be deleted:
del env:\windir


# Deleted environment variables are no longer available:
$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.

# Create a special folder:
md c:\myTools

# Create an example script in this folder:
" 'Hello!' " > c:\myTools\sayHello.ps1

# Usually, you would have to specify a qualified path name:
C:\myTools\sayHello.ps1
Hello!
# The folder is now added to the path environment:
$env:path += ";C:\myTools"

# All scripts and commands can be started immediately in this
# folder simply by entering their name:
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:

# Get file:
$file = Dir c:\autoexec.bat

# File size given by length property:
$file.length

# To embed the file size in text, ad hoc variables are required:
"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:

# Test function with its own local variable scope tries to
# redefine the variable $setValue:
Function Test {$setValue = 99; $setValue }

# Read-only variable is created. Test function may modify this
# value nevertheless by creating a new local variable:
New-Variable setValue -option "ReadOnly" -value 200
Test
99
# Variable is created with the AllScope option and automatically
# copied to local variable scope. Overwriting is now no longer
# possible.
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


路过

雷人

握手

鲜花

鸡蛋

相关阅读

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-8-25 17:14 , Processed in 0.020140 second(s), 16 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

返回顶部