关于变量About Variables

简短说明Short description

描述变量如何存储可在 PowerShell 中使用的值。Describes how variables store values that can be used in PowerShell.

长说明Long description

可以在 PowerShell 变量中存储所有类型的值。You can store all types of values in PowerShell variables. 例如,存储命令的结果,并存储命令和表达式中使用的元素,例如名称、路径、设置和值。For example, store the results of commands, and store elements that are used in commands and expressions, such as names, paths, settings, and values.

变量是存储值的内存单位。A variable is a unit of memory in which values are stored. 在 PowerShell 中,变量由以美元符号开头的文本字符串表示 ($) ,如 $a$process$my_varIn PowerShell, variables are represented by text strings that begin with a dollar sign ($), such as $a, $process, or $my_var.

变量名称不区分大小写,并且可以包含空格和特殊字符。Variable names aren't case-sensitive, and can include spaces and special characters. 但是,包含特殊字符和空格的变量名称难以使用,应避免使用。But, variable names that include special characters and spaces are difficult to use and should be avoided. 有关详细信息,请参阅 包含特殊字符的变量名称For more information, see Variable names that include special characters.

在 PowerShell 中有几种不同类型的变量。There are several different types of variables in PowerShell.

  • 用户创建的变量:用户创建的变量由用户创建和维护。User-created variables: User-created variables are created and maintained by the user. 默认情况下,在 powershell 命令行中创建的变量仅在 PowerShell 窗口处于打开状态时才存在。By default, the variables that you create at the PowerShell command line exist only while the PowerShell window is open. 当 PowerShell 窗口关闭时,这些变量将被删除。When the PowerShell windows is closed, the variables are deleted. 若要保存某个变量,请将其添加到 PowerShell 配置文件中。To save a variable, add it to your PowerShell profile. 你还可以在具有全局、脚本或本地范围的脚本中创建变量。You can also create variables in scripts with global, script, or local scope.

  • 自动变量:自动变量存储 PowerShell 的状态。Automatic variables: Automatic variables store the state of PowerShell. 这些变量由 PowerShell 创建,PowerShell 会根据需要更改它们的值以保持其准确性。These variables are created by PowerShell, and PowerShell changes their values as required to maintain their accuracy. 用户不能更改这些变量的值。Users can't change the value of these variables. 例如, $PSHOME 变量存储 PowerShell 安装目录的路径。For example, the $PSHOME variable stores the path to the PowerShell installation directory.

    有关自动变量的详细信息、列表和说明,请参阅 about_Automatic_VariablesFor more information, a list, and a description of the automatic variables, see about_Automatic_Variables.

  • 首选项变量:首选项为 PowerShell 存储用户首选项。Preference variables: Preference variables store user preferences for PowerShell. 这些变量由 PowerShell 创建,并使用默认值进行填充。These variables are created by PowerShell and are populated with default values. 用户可以更改这些变量的值。Users can change the values of these variables. 例如, $MaximumHistoryCount 变量确定会话历史记录中的最大项数。For example, the $MaximumHistoryCount variable determines the maximum number of entries in the session history.

    有关首选项变量的详细信息、列表和说明,请参阅 about_Preference_VariablesFor more information, a list, and a description of the preference variables, see about_Preference_Variables.

使用变量Working with variables

若要创建新变量,请使用赋值语句为变量赋值。To create a new variable, use an assignment statement to assign a value to the variable. 不需要在使用变量之前先对其进行声明。You don't have to declare the variable before using it. 所有变量的默认值为 $nullThe default value of all variables is $null.

若要获取 PowerShell 会话中所有变量的列表,请键入 Get-VariableTo get a list of all the variables in your PowerShell session, type Get-Variable. 将显示变量名称,其中不含前面的货币 ($ 用于引用变量的) 符号。The variable names are displayed without the preceding dollar ($) sign that is used to reference variables.

例如:For example:

$MyVariable = 1, 2, 3

$Path = "C:\Windows\System32"

变量用于存储命令的结果。Variables are useful for storing the results of commands.

例如:For example:

$Processes = Get-Process

$Today = (Get-Date).DateTime

若要显示变量的值,请键入变量名称,其前面带有美元符号 ($) 。To display the value of a variable, type the variable name, preceded by a dollar sign ($).

例如:For example:

$MyVariable
1
2
3
$Today
Tuesday, September 3, 2019 09:46:46

若要更改变量的值,请将新值分配给该变量。To change the value of a variable, assign a new value to the variable.

下面的示例显示变量的值 $MyVariable ,更改变量的值,然后显示新值。The following examples display the value of the $MyVariable variable, changes the value of the variable, and then displays the new value.

$MyVariable = 1, 2, 3
$MyVariable
1
2
3
$MyVariable = "The green cat."
$MyVariable
The green cat.

若要删除变量的值,请使用 Clear-Variable cmdlet 或将值更改为 $nullTo delete the value of a variable, use the Clear-Variable cmdlet or change the value to $null.

Clear-Variable -Name MyVariable
$MyVariable = $null

若要删除变量,请使用 " 删除变量 " 或 " 删除项"。To delete the variable, use Remove-Variable or Remove-Item.

Remove-Variable -Name MyVariable
Remove-Item -Path Variable:\MyVariable

变量类型Types of variables

可以在变量中存储任何类型的对象,包括整数、字符串、数组和哈希表。You can store any type of object in a variable, including integers, strings, arrays, and hash tables. 和表示进程、服务、事件日志和计算机的对象。And, objects that represent processes, services, event logs, and computers.

PowerShell 变量是松散类型化的,这意味着它们并不限于特定类型的对象。PowerShell variables are loosely typed, which means that they aren't limited to a particular type of object. 单个变量甚至可以同时包含不同类型的对象的集合或数组。A single variable can even contain a collection, or array, of different types of objects at the same time.

变量的数据类型由变量值的 .NET 类型决定。The data type of a variable is determined by the .NET types of the values of the variable. 若要查看变量的对象类型,请使用 Get MemberTo view a variable's object type, use Get-Member.

例如:For example:

$a = 12                         # System.Int32
$a = "Word"                     # System.String
$a = 12, "Word"                 # array of System.Int32, System.String
$a = Get-ChildItem C:\Windows   # FileInfo and DirectoryInfo types

您可以使用类型属性和强制转换表示法来确保变量只能包含特定的对象类型或可转换为该类型的对象。You can use a type attribute and cast notation to ensure that a variable can contain only specific object types or objects that can be converted to that type. 如果尝试分配另一个类型的值,则 PowerShell 会尝试将值转换为其类型。If you try to assign a value of another type, PowerShell tries to convert the value to its type. 如果无法转换类型,赋值语句将失败。If the type can't be converted, the assignment statement fails.

若要使用强制转换表示法,请在赋值语句左侧) (的变量名称之前输入类型名称(括在括号中)。To use cast notation, enter a type name, enclosed in brackets, before the variable name (on the left side of the assignment statement). 下面的示例创建一个 $number 变量,该变量只能包含整数、只能包含字符串的变量 $words ,以及只能 $dates 包含 DateTime 对象的变量。The following example creates a $number variable that can contain only integers, a $words variable that can contain only strings, and a $dates variable that can contain only DateTime objects.

[int]$number = 8
$number = "12345"  # The string is converted to an integer.
$number = "Hello"
Cannot convert value "Hello" to type "System.Int32". Error: "Input string was
 not in a correct format."
At line:1 char:1
+ $number = "Hello"
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo          : MetadataError: (:) [],
    ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException
[string]$words = "Hello"
$words = 2       # The integer is converted to a string.
$words += 10     # The plus (+) sign concatenates the strings.
$words
210
[datetime] $dates = "09/12/91"  # The string is converted to a DateTime object.
$dates
Thursday, September 12, 1991 00:00:00
$dates = 10    # The integer is converted to a DateTime object.
$dates
Monday, January 1, 0001 00:00:00

在命令和表达式中使用变量Using variables in commands and expressions

若要在命令或表达式中使用变量,请键入变量名称,前面加上美元 ($) 符号。To use a variable in a command or expression, type the variable name, preceded by the dollar ($) sign.

如果变量名和美元符号没有用引号引起来,或者它们括在双引号 (") 标记中,则在命令或表达式中使用该变量的值。If the variable name and dollar sign aren't enclosed in quotation marks, or if they're enclosed in double quotation (") marks, the value of the variable is used in the command or expression.

如果变量名和美元符号用单引号引起 (') 标记,则在表达式中使用变量名。If the variable name and dollar sign are enclosed in single quotation (') marks, the variable name is used in the expression.

有关在 PowerShell 中使用引号的详细信息,请参阅 about_Quoting_RulesFor more information about using quotation marks in PowerShell, see about_Quoting_Rules.

此示例获取变量的值 $PROFILE ,它是 powershell 控制台中 powershell 用户配置文件的路径。This example gets the value of the $PROFILE variable, which is the path to the PowerShell user profile file in the PowerShell console.

$PROFILE
C:\Users\User01\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

在此示例中,显示了两个命令,可在 notepad.exe 中打开 PowerShell 配置文件。In this example, two commands are shown that can open the PowerShell profile in notepad.exe. 带有双引号 () 标记的示例 " 使用变量的值。The example with double-quote (") marks uses the variable's value.

notepad $PROFILE

notepad "$PROFILE"

下面的示例使用单引号 (将 ' 变量视为文本的) 标记。The following examples use single-quote (') marks that treat the variable as literal text.

'$PROFILE'
$PROFILE
'Use the $PROFILE variable.'
Use the $PROFILE variable.

包含特殊字符的变量名称Variable names that include special characters

变量名称以美元 ($) 符号开头,可以包含字母数字字符和特殊字符。Variable names begin with a dollar ($) sign and can include alphanumeric characters and special characters. 变量名称长度仅受可用内存的限制。The variable name length is limited only by available memory.

最佳做法是,变量名称只能包含字母数字字符和下划线 (_) 字符。The best practice is that variable names include only alphanumeric characters and the underscore (_) character. 包含空格和其他特殊字符的变量名称难以使用,应避免使用。Variable names that include spaces and other special characters, are difficult to use and should be avoided.

字母数字变量名可以包含以下字符:Alphanumeric variable names can contain these characters:

  • 这些类别中的 Unicode 字符: LuLlLtLmLoNdUnicode characters from these categories: Lu , Ll , Lt , Lm , Lo , or Nd.
  • 下划线 (_) 字符。Underscore (_) character.
  • 问号 (?) 字符。Question mark (?) character.

下面的列表包含 Unicode 类别说明。The following list contains the Unicode category descriptions. 有关详细信息,请参阅 system.globalization.unicodecategoryFor more information, see UnicodeCategory.

  • Lu -UppercaseLetterLu - UppercaseLetter
  • Ll -LowercaseLetterLl - LowercaseLetter
  • Lt -TitlecaseLetterLt - TitlecaseLetter
  • Lm -ModifierLetterLm - ModifierLetter
  • Lo -OtherLetterLo - OtherLetter
  • Nd -DecimalDigitNumberNd - DecimalDigitNumber

若要创建或显示包含空格或特殊字符的变量名称,请使用大括号将该变量名称括 ({}) 字符。To create or display a variable name that includes spaces or special characters, enclose the variable name with the curly braces ({}) characters. 大括号直接 PowerShell 将变量名称的字符解释为文本。The curly braces direct PowerShell to interpret the variable name's characters as literals.

特殊字符变量名称可以包含以下字符:Special character variable names can contain these characters:

  • 任何 Unicode 字符,但以下情况除外:Any Unicode character, with the following exceptions:
    • 右大括号 (}) 字符 (U + 007D) 。The closing curly brace (}) character (U+007D).
    • 反撇号 (`) 字符 (U + 0060) 。The backtick (`) character (U+0060). 反撇号用于对 Unicode 字符进行转义,以使它们被视为文本。The backtick is used to escape Unicode characters so they're treated as literals.

PowerShell 包含 $$ $? $^ $_ 包含字母数字字符和特殊字符的保留变量,如、、和。PowerShell has reserved variables such as $$, $?, $^, and $_ that contain alphanumeric and special characters. 有关详细信息,请参阅 about_Automatic_VariablesFor more information, see about_Automatic_Variables.

例如,以下命令将创建名为的变量 save-itemsFor example, the following command creates the variable named save-items. 需要大括号 ({}) ,因为变量名称包含连字符 (-) 特殊字符。The curly braces ({}) are needed because variable name includes a hyphen (-) special character.

${save-items} = "a", "b", "c"
${save-items}
a
b
c

以下命令将获取由环境变量表示的目录中的子项目 ProgramFiles(x86)The following command gets the child items in the directory that is represented by the ProgramFiles(x86) environment variable.

Get-ChildItem ${env:ProgramFiles(x86)}

若要引用包含大括号的变量名,请将变量名称括在大括号中,并使用反撇号字符来转义大括号。To reference a variable name that includes braces, enclose the variable name in braces, and use the backtick character to escape the braces. 例如,若要创建名为 type 的变量 this{value}isFor example, to create a variable named this{value}is type:

${this`{value`}is} = "This variable name uses braces and backticks."
${this`{value`}is}
This variable name uses braces and backticks.

变量和范围Variables and scope

默认情况下,变量仅在创建它们的范围内可用。By default, variables are only available in the scope in which they're created.

例如,在函数中创建的变量仅在函数内可用。For example, a variable that you create in a function is available only within the function. 在脚本中创建的变量仅在脚本内可用。A variable that you create in a script is available only within the script. 如果脚本为点,则将变量添加到当前作用域。If you dot-source the script, the variable is added to the current scope. 有关详细信息,请参阅 about_ScopesFor more information, see about_Scopes.

您可以使用作用域修饰符来更改变量的默认作用域。You can use a scope modifier to change the default scope of the variable. 下面的表达式创建一个名为的变量 ComputersThe following expression creates a variable named Computers. 尽管变量是在脚本或函数中创建的,但它也具有全局作用域。The variable has a global scope, even when it's created in a script or function.

$Global:Computers = "Server01"

对于任何执行进程外的脚本或命令,都需要 Using 范围修饰符来嵌入调用会话范围内的变量值,以便使会话代码不能访问它们。For any script or command that executes out of session, you need the Using scope modifier to embed variable values from the calling session scope, so that out of session code can access them.

有关详细信息,请参阅 about_Remote_VariablesFor more information, see about_Remote_Variables.

保存变量Saving variables

你创建的变量仅在创建它们的会话中可用。Variables that you create are available only in the session in which you create them. 关闭会话时,它们会丢失。They're lost when you close your session.

若要在启动的每个 PowerShell 会话中创建变量,请将变量添加到 PowerShell 配置文件。To create the variable in every PowerShell session that you start, add the variable to your PowerShell profile.

例如,若要 $VerbosePreference 在每个 powershell 会话中更改变量的值,请将以下命令添加到 powershell 配置文件中。For example, to change the value of the $VerbosePreference variable in every PowerShell session, add the following command to your PowerShell profile.

$VerbosePreference = "Continue"

可以通过 $PROFILE 在文本编辑器中打开文件(如 notepad.exe ),将此命令添加到 PowerShell 配置文件。You can add this command to your PowerShell profile by opening the $PROFILE file in a text editor, such as notepad.exe. 有关 PowerShell 配置文件的详细信息,请参阅 about_ProfilesFor more information about PowerShell profiles, see about_Profiles.

变量:驱动器The Variable: drive

PowerShell 变量提供程序创建的 Variable: 驱动器的外观和行为类似于文件系统驱动器,但它包含会话中的变量及其值。The PowerShell Variable provider creates a Variable: drive that looks and acts like a file system drive, but it contains the variables in your session and their values.

若要切换到 Variable: 驱动器,请使用以下命令:To change to the Variable: drive, use the following command:

Set-Location Variable:

若要列出驱动器中的项和变量 Variable: ,请使用 Get-ItemGet-ChildItem cmdlet。To list the items and variables in the Variable: drive, use the Get-Item or Get-ChildItem cmdlets.

Get-ChildItem Variable:

若要获取特定变量的值,请使用文件系统表示法指定驱动器名称和变量名称。To get the value of a particular variable, use file system notation to specify the name of the drive and the name of the variable. 例如,若要获取 $PSCulture 自动变量,请使用以下命令。For example, to get the $PSCulture automatic variable, use the following command.

Get-Item Variable:\PSCulture
Name                           Value
----                           -----
PSCulture                      en-US

若要显示有关 Variable: 驱动器和 PowerShell Variable 提供程序的详细信息,请键入:To display more information about the Variable: drive and the PowerShell Variable provider, type:

Get-Help Variable

具有提供程序路径的变量语法Variable syntax with provider paths

你可以为提供程序路径加上前缀 ($) 符号,并访问实现 IContentCmdletProvider 接口的任何提供程序的内容。You can prefix a provider path with the dollar ($) sign, and access the content of any provider that implements the IContentCmdletProvider interface.

以下内置 PowerShell 提供程序支持此表示法:The following built-in PowerShell providers support this notation:

变量 cmdletThe variable cmdlets

PowerShell 包括一组旨在管理变量的 cmdlet。PowerShell includes a set of cmdlets that are designed to manage variables.

若要列出这些 cmdlet,请键入:To list the cmdlets, type:

Get-Command -Noun Variable

若要获取特定 cmdlet 的帮助,请键入:To get help for a specific cmdlet, type:

Get-Help <cmdlet-name>
Cmdlet 名称Cmdlet Name 说明Description
Clear-Variable 删除变量的值。Deletes the value of a variable.
Get-Variable 获取当前控制台中的变量。Gets the variables in the current console.
New-Variable 创建新变量。Creates a new variable.
Remove-Variable 删除变量及其值。Deletes a variable and its value.
Set-Variable 更改变量的值。Changes the value of a variable.

另请参阅See also

about_Automatic_Variablesabout_Automatic_Variables

about_Environment_Variablesabout_Environment_Variables

about_Preference_Variablesabout_Preference_Variables

about_Profilesabout_Profiles

about_Quoting_Rulesabout_Quoting_Rules

about_Scopesabout_Scopes

about_Remote_Variablesabout_Remote_Variables