关于自动变量About Automatic Variables

简短说明Short description

描述存储 PowerShell 的状态信息的变量。Describes variables that store state information for PowerShell. 这些变量由 PowerShell 创建和维护。These variables are created and maintained by PowerShell.

长说明Long description

从概念上讲,这些变量被视为只读。Conceptually, these variables are considered to be read-only. 即使 将它们写入到中,但 不应 将其写入到后向兼容性。Even though they can be written to, for backward compatibility they should not be written to.

下面是 PowerShell 中自动变量的列表:Here is a list of the automatic variables in PowerShell:

$$

包含会话收到的最后一行中的最后一个标记。Contains the last token in the last line received by the session.

$?$?

包含最后一个命令的执行状态。Contains the execution status of the last command. 如果最后一个命令成功,则 为 True; 否则为 FalseIt contains True if the last command succeeded and False if it failed.

对于在管道中的多个阶段(例如在和块中)运行的 cmdlet 和高级函数,在 process end this.WriteError() 任何点调用或分别调用或 $PSCmdlet.WriteError() 分别将设置 $?False,就像 this.ThrowTerminatingError()$PSCmdlet.ThrowTerminatingError()For cmdlets and advanced functions that are run at multiple stages in a pipeline, for example in both process and end blocks, calling this.WriteError() or $PSCmdlet.WriteError() respectively at any point will set $? to False, as will this.ThrowTerminatingError() and $PSCmdlet.ThrowTerminatingError().

Write-ErrorCmdlet 始终在 $? 执行后立即设置为 false ,但不会 $? 对调用它的函数设置为 falseThe Write-Error cmdlet always sets $? to False immediately after it is executed, but will not set $? to False for a function calling it:

function Test-WriteError
{
    Write-Error "Bad"
    $? # $false
}

Test-WriteError
$? # $true

对于后一种用途, $PSCmdlet.WriteError() 应改为使用。For the latter purpose, $PSCmdlet.WriteError() should be used instead.

对于 (可执行文件) 的本机命令, $? 当为0时,将设置为 True $LASTEXITCODE ,如果 $LASTEXITCODE 为任何其他值,则设置为 False。For native commands (executables), $? is set to True when $LASTEXITCODE is 0, and set to False when $LASTEXITCODE is any other value.

备注

在 PowerShell 7 中,在括号内包含语句后 (...) ,子表达式语法 $(...) 或数组表达式 @(...) 始终重置 $?True,因此 (Write-Error) 显示 $?trueUntil PowerShell 7, containing a statement within parentheses (...), subexpression syntax $(...) or array expression @(...) always reset $? to True, so that (Write-Error) shows $? as True. 此操作在 PowerShell 7 中已更改,因此 $? 将始终反映在这些表达式中运行的最后一个命令的实际成功。This has been changed in PowerShell 7, so that $? will always reflect the actual success of the last command run in these expressions.

$^

包含会话收到的最后一行中的第一个标记。Contains the first token in the last line received by the session.

$$

$PSItem 相同。Same as $PSItem. 包含管道对象中的当前对象。Contains the current object in the pipeline object. 可以在对每个对象或管道中的选定对象执行操作的命令中使用此变量。You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

$args$args

包含传递给函数、脚本或脚本块的未声明参数的值数组。Contains an array of values for undeclared parameters that are passed to a function, script, or script block. 创建函数时,可以使用 param 关键字或在函数名称后的括号中添加以逗号分隔的参数列表,来声明参数。When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name.

在事件操作中, $args 变量包含表示正在处理的事件的事件参数的对象。In an event action, the $args variable contains objects that represent the event arguments of the event that is being processed. 仅在 Action 事件注册命令块内填充此变量。This variable is populated only within the Action block of an event registration command. 此变量的值还可在返回的 PSEventArgs 对象的 SourceArgs 属性中找到 Get-EventThe value of this variable can also be found in the SourceArgs property of the PSEventArgs object that Get-Event returns.

$ConsoleFileName$ConsoleFileName

包含 .psc1 会话中最近使用的控制台文件 () 的路径。Contains the path of the console file (.psc1) that was most recently used in the session. 使用 PSConsoleFile 参数启动 PowerShell 或使用 Export-Console cmdlet 将管理单元名称导出到控制台文件时,将填充此变量。This variable is populated when you start PowerShell with the PSConsoleFile parameter or when you use the Export-Console cmdlet to export snap-in names to a console file.

使用 Export-Console 不带参数的 cmdlet 时,它会自动更新会话中最近使用的控制台文件。When you use the Export-Console cmdlet without parameters, it automatically updates the console file that was most recently used in the session. 您可以使用此自动变量来确定将更新哪个文件。You can use this automatic variable to determine which file will be updated.

$Error$Error

包含错误对象的数组,这些对象表示最近的错误。Contains an array of error objects that represent the most recent errors. 最近的错误是数组中第一个错误对象 $Error[0]The most recent error is the first error object in the array $Error[0].

若要防止将错误添加到 $Error 数组,请使用值为 IgnoreErrorAction 通用参数。To prevent an error from being added to the $Error array, use the ErrorAction common parameter with a value of Ignore. 有关详细信息,请参阅 about_CommonParametersFor more information, see about_CommonParameters.

$Event$Event

包含表示正在处理的事件的 PSEventArgs 对象。Contains a PSEventArgs object that represents the event that is being processed. 此变量仅在 Action 事件注册命令块中填充,例如 Register-ObjectEventThis variable is populated only within the Action block of an event registration command, such as Register-ObjectEvent. 此变量的值与 cmdlet 返回的对象相同 Get-EventThe value of this variable is the same object that the Get-Event cmdlet returns. 因此,可以 Event $Event.TimeGenerated 在脚本块中使用该变量的属性,例如 ActionTherefore, you can use the properties of the Event variable, such as $Event.TimeGenerated, in an Action script block.

$EventArgs$EventArgs

包含一个对象,该对象表示从正在处理的事件的 EventArgs 派生的第一个事件参数。Contains an object that represents the first event argument that derives from EventArgs of the event that is being processed. 仅在 Action 事件注册命令块内填充此变量。This variable is populated only within the Action block of an event registration command. 此变量的值还可在返回的 PSEventArgs 对象的 SourceEventArgs 属性中找到 Get-EventThe value of this variable can also be found in the SourceEventArgs property of the PSEventArgs object that Get-Event returns.

$EventSubscriber$EventSubscriber

包含一个 PSEventSubscriber 对象,该对象表示正在处理的事件的事件订阅服务器。Contains a PSEventSubscriber object that represents the event subscriber of the event that is being processed. 仅在 Action 事件注册命令块内填充此变量。This variable is populated only within the Action block of an event registration command. 此变量的值与 cmdlet 返回的对象相同 Get-EventSubscriberThe value of this variable is the same object that the Get-EventSubscriber cmdlet returns.

$ExecutionContext$ExecutionContext

包含一个 EngineIntrinsics 对象,该对象表示 PowerShell 主机的执行上下文。Contains an EngineIntrinsics object that represents the execution context of the PowerShell host. 您可以使用此变量来查找可用于 cmdlet 的执行对象。You can use this variable to find the execution objects that are available to cmdlets.

$false$false

包含 FalseContains False. 可以在命令和脚本中使用此变量来表示 False ,而不是使用字符串 "False"。You can use this variable to represent False in commands and scripts instead of using the string "false". 如果字符串被转换为非空字符串或非零整数,则可以将该字符串解释为 TrueThe string can be interpreted as True if it's converted to a non-empty string or to a non-zero integer.

$foreach$foreach

包含枚举器 (不是 ForEach 循环) 的结果值。Contains the enumerator (not the resulting values) of a ForEach loop. $ForEach 变量仅在 ForEach 循环运行时存在; 在循环完成后将其删除。The $ForEach variable exists only while the ForEach loop is running; it's deleted after the loop is completed.

枚举器包含可用于检索循环值和更改当前循环迭代的属性和方法。Enumerators contain properties and methods you can use to retrieve loop values and change the current loop iteration. 有关详细信息,请参阅 使用枚举器。For more information, see Using Enumerators.

$HOME$HOME

包含用户的主目录的完整路径。Contains the full path of the user's home directory. 通常,此变量等效于 "$env:homedrive$env:homepath" Windows 环境变量 C:\Users\<UserName>This variable is the equivalent of the "$env:homedrive$env:homepath" Windows environment variables, typically C:\Users\<UserName>.

$Host$Host

包含表示 PowerShell 的当前主机应用程序的对象。Contains an object that represents the current host application for PowerShell. 您可以使用此变量来表示命令中的当前宿主,或者显示或更改主机的属性,例如 $Host.version$Host.CurrentCulture $host.ui.rawui.setbackgroundcolor("Red")You can use this variable to represent the current host in commands or to display or change the properties of the host, such as $Host.version or $Host.CurrentCulture, or $host.ui.rawui.setbackgroundcolor("Red").

$input$input

包含枚举传递到函数的所有输入的枚举器。Contains an enumerator that enumerates all input that is passed to a function. $input 变量仅适用于) 为未命名函数 (函数和脚本块。The $input variable is available only to functions and script blocks (which are unnamed functions).

  • 在没有 Begin 、或块的函数中 Process End$input 变量枚举函数的所有输入的集合。In a function without a Begin, Process, or End block, the $input variable enumerates the collection of all input to the function.

  • Begin 块中, $input 变量不包含任何数据。In the Begin block, the $input variable contains no data.

  • Process 块中, $input 变量包含管道中当前的对象。In the Process block, the $input variable contains the object that is currently in the pipeline.

  • End 块中, $input 变量枚举函数的所有输入的集合。In the End block, the $input variable enumerates the collection of all input to the function.

    备注

    不能 $input 在同一函数或脚本块中的进程块和结束块中使用该变量。You cannot use the $input variable inside both the Process block and the End block in the same function or script block.

由于 $input 是一个枚举器,因此访问它的任何属性都将导致 $input 不再可用。Since $input is an enumerator, accessing any of it's properties causes $input to no longer be available. 可以 $input 在另一个变量中存储以重用 $input 属性。You can store $input in another variable to reuse the $input properties.

枚举器包含可用于检索循环值和更改当前循环迭代的属性和方法。Enumerators contain properties and methods you can use to retrieve loop values and change the current loop iteration. 有关详细信息,请参阅 使用枚举器。For more information, see Using Enumerators.

$input -Command pwsh 当从命令行调用时,该变量也可用于由的参数指定的命令。The $input variable is also available to the command specified by the -Command parameter of pwsh when invoked from the command line. 下面的示例从 Windows 命令行界面运行。The following example is run from the Windows Command shell.

echo Hello | pwsh -Command """$input World!"""

$IsCoreCLR$IsCoreCLR

包含 $True 当前会话是否在 .Net Core 运行时上运行 (CoreCLR) 。Contains $True if the current session is running on the .NET Core Runtime (CoreCLR). 否则包含 $FalseOtherwise contains $False.

$IsLinux$IsLinux

包含 $True 当前会话是否在 Linux 操作系统上运行。Contains $True if the current session is running on a Linux operating system. 否则包含 $FalseOtherwise contains $False.

$IsMacOS$IsMacOS

包含 $True 当前会话是否在 MacOS 操作系统上运行的。Contains $True if the current session is running on a MacOS operating system. 否则包含 $FalseOtherwise contains $False.

$IsWindows$IsWindows

$TRUE如果当前会话正在 Windows 操作系统上运行,则包含。Contains $TRUE if the current session is running on a Windows operating system. 否则包含 $FALSEOtherwise contains $FALSE.

$LastExitCode$LastExitCode

包含上一次运行的基于 Windows 的程序的退出代码。Contains the exit code of the last Windows-based program that was run.

$Matches$Matches

Matches变量与 -match and 运算符一起使用 -notmatchThe Matches variable works with the -match and -notmatch operators. 当你将标量输入提交给 -match or -notmatch 运算符,并且其中一个检测到匹配时,它们将返回一个布尔值,并 $Matches 使用匹配的任何字符串值的哈希表填充自动变量。When you submit scalar input to the -match or -notmatch operator, and either one detects a match, they return a Boolean value and populate the $Matches automatic variable with a hash table of any string values that were matched. $Matches 将正则表达式用于运算符时,还可以使用捕获来填充哈希表 -matchThe $Matches hash table can also be populated with captures when you use regular expressions with the -match operator.

有关运算符的详细信息 -match ,请参阅 about_Comparison_OperatorsFor more information about the -match operator, see about_Comparison_Operators. 有关正则表达式的详细信息,请参阅 about_Regular_ExpressionsFor more information on regular expressions, see about_Regular_Expressions.

$MyInvocation$MyInvocation

包含有关当前命令的信息,如名称、参数、参数值和有关如何启动、调用或调用命令的信息,例如调用当前命令的脚本的名称。Contains information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or invoked, such as the name of the script that called the current command.

$MyInvocation 仅填充脚本、函数和脚本块。$MyInvocation is populated only for scripts, function, and script blocks. 您可以使用在当前脚本中返回的 InvocationInfo 对象中的信息 $MyInvocation ,例如脚本 () 的路径和文件名, $MyInvocation.MyCommand.Path 或函数的名称 ($MyInvocation.MyCommand.Name) 以标识当前命令。You can use the information in the System.Management.Automation.InvocationInfo object that $MyInvocation returns in the current script, such as the path and file name of the script ($MyInvocation.MyCommand.Path) or the name of a function ($MyInvocation.MyCommand.Name) to identify the current command. 这对于查找当前脚本的名称特别有用。This is particularly useful for finding the name of the current script.

从 PowerShell 3.0 开始, MyInvocation 具有以下新属性。Beginning in PowerShell 3.0, MyInvocation has the following new properties.

属性Property 说明Description
PSScriptRootPSScriptRoot 包含调用的脚本的完整路径Contains the full path to the script that invoked
当前命令。the current command. 此属性的值为The value of this property is
仅当调用方为脚本时才填充。populated only when the caller is a script.
PSCommandPathPSCommandPath 包含脚本的完整路径和文件名Contains the full path and file name of the script
调用当前命令的。that invoked the current command. 此的值The value of this
仅当调用方是property is populated only when the caller is a
脚本。script.

与自动变量不同 $PSScriptRoot $PSCommandPath ,自动变量的 PSScriptRootPSCommandPath 属性 $MyInvocation 包含有关调用程序或调用脚本的信息,而不是当前脚本。Unlike the $PSScriptRoot and $PSCommandPath automatic variables, the PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script.

$NestedPromptLevel$NestedPromptLevel

包含当前提示符级别。Contains the current prompt level. 值0表示原始提示级别。A value of 0 indicates the original prompt level. 当您输入嵌套级别时,该值会递增,并且在您退出时将递增。The value is incremented when you enter a nested level and decremented when you exit it.

例如,使用方法时,PowerShell 会显示嵌套的命令提示符 $Host.EnterNestedPromptFor example, PowerShell presents a nested command prompt when you use the $Host.EnterNestedPrompt method. 当你到达 PowerShell 调试器中的断点时,PowerShell 还会显示嵌套的命令提示符。PowerShell also presents a nested command prompt when you reach a breakpoint in the PowerShell debugger.

输入嵌套提示符时,PowerShell 将暂停当前命令,保存执行上下文,并递增变量的值 $NestedPromptLevelWhen you enter a nested prompt, PowerShell pauses the current command, saves the execution context, and increments the value of the $NestedPromptLevel variable. 若要创建其他嵌套的命令提示 (最多128级别) 或返回到原始命令提示符,请完成命令或键入 exitTo create additional nested command prompts (up to 128 levels) or to return to the original command prompt, complete the command, or type exit.

$NestedPromptLevel变量有助于跟踪提示级别。The $NestedPromptLevel variable helps you track the prompt level. 你可以创建一个包含此值的备用 PowerShell 命令提示符,以使其始终可见。You can create an alternative PowerShell command prompt that includes this value so that it's always visible.

$null$null

$null 是包含 null 值或空值的自动变量。$null is an automatic variable that contains a null or empty value. 您可以使用此变量来表示命令和脚本中缺少的值或未定义的值。You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell 将视为 $null 具有值的对象(即,作为显式占位符),因此可以使用 $null 来表示一系列值中的空值。PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

例如,当 $null 包含在集合中时,会将其计为一个对象。For example, when $null is included in a collection, it's counted as one of the objects.

$a = "one", $null, "three"
$a.count
3

如果通过管道将 $null 变量传递给 ForEach-Object cmdlet,它会为生成一个值 $null ,就像对其他对象执行此方法一样。If you pipe the $null variable to the ForEach-Object cmdlet, it generates a value for $null, just as it does for the other objects

"one", $null, "three" | ForEach-Object { "Hello " + $_}
Hello one
Hello
Hello three

因此,不能使用 $null 来表示 没有参数值As a result, you can't use $null to mean no parameter value. 参数值 $null 覆盖默认参数值。A parameter value of $null overrides the default parameter value.

但是,因为 PowerShell 将 $null 变量视为占位符,所以可以在脚本中使用它,如果忽略,这将不起作用 $nullHowever, because PowerShell treats the $null variable as a placeholder, you can use it in scripts like the following one, which wouldn't work if $null were ignored.

$calendar = @($null, $null, "Meeting", $null, $null, "Team Lunch", $null)
$days = "Sunday","Monday","Tuesday","Wednesday","Thursday",
        "Friday","Saturday"
$currentDay = 0
foreach($day in $calendar)
{
    if($day -ne $null)
    {
        "Appointment on $($days[$currentDay]): $day"
    }

    $currentDay++
}
Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch

$PID$PID

包含承载当前 PowerShell 会话的进程的进程标识符 (PID) 。Contains the process identifier (PID) of the process that is hosting the current PowerShell session.

$PROFILE$PROFILE

包含当前用户和当前主机应用程序的 PowerShell 配置文件的完整路径。Contains the full path of the PowerShell profile for the current user and the current host application. 您可以使用此变量来表示命令中的配置文件。You can use this variable to represent the profile in commands. 例如,你可以在命令中使用它来确定是否已创建配置文件:For example, you can use it in a command to determine whether a profile has been created:

Test-Path $PROFILE

或者,你可以在命令中使用它来创建配置文件:Or, you can use it in a command to create a profile:

New-Item -ItemType file -Path $PROFILE -Force

可以在命令中使用它在 notepad.exe 中打开配置文件:You can use it in a command to open the profile in notepad.exe:

notepad.exe $PROFILE

$PSBoundParameters$PSBoundParameters

包含传递给脚本或函数的参数的字典及其当前值。Contains a dictionary of the parameters that are passed to a script or function and their current values. 此变量仅在声明参数的作用域(如脚本或函数)中具有值。This variable has a value only in a scope where parameters are declared, such as a script or function. 您可以使用它显示或更改参数的当前值,或者将参数值传递给其他脚本或函数。You can use it to display or change the current values of parameters or to pass parameter values to another script or function.

在此示例中, Test2 函数将传递 $PSBoundParametersTest1 函数。In this example, the Test2 function passes the $PSBoundParameters to the Test1 function. $PSBoundParameters 的格式显示。The $PSBoundParameters are displayed in the format of Key and Value.

function Test1 {
   param($a, $b)

   # Display the parameters in dictionary format.
   $PSBoundParameters
}

function Test2 {
   param($a, $b)

   # Run the Test1 function with $a and $b.
   Test1 @PSBoundParameters
}
Test2 -a Power -b Shell
Key   Value
---   -----
a     Power
b     Shell

$PSCmdlet$PSCmdlet

包含一个对象,该对象表示正在运行的 cmdlet 或高级函数。Contains an object that represents the cmdlet or advanced function that's being run.

你可以使用 cmdlet 或函数代码中的对象的属性和方法来响应使用情况。You can use the properties and methods of the object in your cmdlet or function code to respond to the conditions of use. 例如, ParameterSetName 属性包含所使用的参数集的名称, ShouldProcess 方法会动态地将 WhatIfConfirm 参数添加到 cmdlet。For example, the ParameterSetName property contains the name of the parameter set that's being used, and the ShouldProcess method adds the WhatIf and Confirm parameters to the cmdlet dynamically.

有关自动变量的详细信息 $PSCmdlet ,请参阅 about_Functions_CmdletBindingAttributeabout_Functions_AdvancedFor more information about the $PSCmdlet automatic variable, see about_Functions_CmdletBindingAttribute and about_Functions_Advanced.

$PSCommandPath$PSCommandPath

包含正在运行的脚本的完整路径和文件名。Contains the full path and file name of the script that's being run. 此变量在所有脚本中都有效。This variable is valid in all scripts.

$PSCulture$PSCulture

从 PowerShell 7 开始, $PSCulture 反映当前 PowerShell 运行空间的区域性 (会话) 。Beginning in PowerShell 7, $PSCulture reflects the culture of the current PowerShell runspace (session). 如果在 PowerShell 运行空间中更改了区域性,则将 $PSCulture 更新该运行空间的值。If the culture is changed in a PowerShell runspace, the $PSCulture value for that runspace is updated.

区域性确定项的显示格式(例如数字、货币和日期),并将其存储在 system.exception 对象中。The culture determines the display format of items such as numbers, currency, and dates, and is stored in a System.Globalization.CultureInfo object. 用于 Get-Culture 显示计算机的区域性。Use Get-Culture to display the computer's culture. $PSCulture 包含 名称 属性的值。$PSCulture contains the Name property's value.

$PSDebugContext$PSDebugContext

调试时,此变量包含有关调试环境的信息。While debugging, this variable contains information about the debugging environment. 否则,它将包含 null 值。Otherwise, it contains a null value. 因此,你可以使用它来指示调试器是否具有控件。As a result, you can use it to indicate whether the debugger has control. 填充后,它将包含一个 PsDebugContext 对象,该对象具有 断点InvocationInfo 属性。When populated, it contains a PsDebugContext object that has Breakpoints and InvocationInfo properties. InvocationInfo 属性具有多个有用的属性,包括 Location 属性。The InvocationInfo property has several useful properties, including the Location property. Location 属性指示正在调试的脚本的路径。The Location property indicates the path of the script that is being debugged.

$PSHOME$PSHOME

包含适用于 PowerShell 的安装目录的完整路径,通常是 $env:windir\System32\PowerShell\v1.0 在 Windows 系统中。Contains the full path of the installation directory for PowerShell, typically, $env:windir\System32\PowerShell\v1.0 in Windows systems. 可以在 PowerShell 文件的路径中使用此变量。You can use this variable in the paths of PowerShell files. 例如,下面的命令在概念帮助主题中搜索 word 变量For example, the following command searches the conceptual Help topics for the word variable:

Select-String -Pattern Variable -Path $pshome\*.txt

$PSItem$PSItem

$_ 相同。Same as $_. 包含管道对象中的当前对象。Contains the current object in the pipeline object. 可以在对每个对象或管道中的选定对象执行操作的命令中使用此变量。You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

$PSScriptRoot$PSScriptRoot

包含正在从中运行脚本的目录。Contains the directory from which a script is being run.

在 PowerShell 2.0 中,此变量仅在) 的脚本模块中有效 (.psm1In PowerShell 2.0, this variable is valid only in script modules (.psm1). 从 PowerShell 3.0 开始,它在所有脚本中都有效。Beginning in PowerShell 3.0, it's valid in all scripts.

$PSSenderInfo$PSSenderInfo

包含有关启动 PSSession 的用户的信息,其中包括源计算机的用户标识和时区。Contains information about the user who started the PSSession, including the user identity and the time zone of the originating computer. 此变量仅在 Pssession 中可用。This variable is available only in PSSessions.

$PSSenderInfo 变量包含一个用户可配置的属性 ApplicationArguments,默认情况下,该属性仅包含 $PSVersionTable 来自原始会话的。The $PSSenderInfo variable includes a user-configurable property, ApplicationArguments, that by default, contains only the $PSVersionTable from the originating session. 若要将数据添加到 ApplicationArguments 属性,请使用 Cmdlet 的 ApplicationArguments 参数 New-PSSessionOptionTo add data to the ApplicationArguments property, use the ApplicationArguments parameter of the New-PSSessionOption cmdlet.

$PSUICulture$PSUICulture

包含操作系统中当前正在使用的 (UI) 区域性的用户界面的名称。Contains the name of the user interface (UI) culture that's currently in use in the operating system. UI 区域性确定哪些文本字符串用于用户界面元素,例如菜单和消息。The UI culture determines which text strings are used for user interface elements, such as menus and messages. 这是系统的 System.Globalization.CultureInfo.CurrentUICulture.Name 属性的值。This is the value of the System.Globalization.CultureInfo.CurrentUICulture.Name property of the system. 若要获取 系统的 system.servicemodel 对象, 请使用 Get-UICulture cmdlet。To get the System.Globalization.CultureInfo object for the system, use the Get-UICulture cmdlet.

$PSVersionTable$PSVersionTable

包含一个只读的哈希表,该表显示有关当前会话中正在运行的 PowerShell 版本的详细信息。Contains a read-only hash table that displays details about the version of PowerShell that is running in the current session. 该表包含以下各项:The table includes the following items:

属性Property 说明Description
PSVersionPSVersion PowerShell 版本号The PowerShell version number
PSEditionPSEdition 此属性的值为 "Desktop"This property has the value of 'Desktop' for
PowerShell 4 及更低PowerShell 4 and below as well as PowerShell
5.1 功能齐全的 Windows 版本。5.1 on full-featured Windows editions.
此属性的值为 "Core"This property has the value of 'Core' for
PowerShell 6 及更高版本以及 PowerShellPowerShell 6 and above as well as PowerShell
精简版的小型版本上的 PowerShell 5。1PowerShell 5.1 on reduced-footprint editions
类似于 Windows Nano Server 或 Windows IoT。like Windows Nano Server or Windows IoT.
GitCommitIdGitCommitId GitHub 中的源文件的提交 IdThe commit Id of the source files, in GitHub,
OSOS 操作系统的说明Description of the operating system that
PowerShell 正在上运行。PowerShell is running on.
平台Platform 操作系统正在运行的平台Platform that the operating system is running
如果on. Linux 和 macOS 上的值为 UnixThe value on Linux and macOS is Unix.
请参见 $IsMacOs$IsLinuxSee $IsMacOs and $IsLinux.
PSCompatibleVersionsPSCompatibleVersions 兼容的 PowerShell 版本Versions of PowerShell that are compatible
与当前版本with the current version
PSRemotingProtocolVersionPSRemotingProtocolVersion PowerShell 远程的版本The version of the PowerShell remote
管理协议。management protocol.
SerializationVersionSerializationVersion 序列化方法的版本The version of the serialization method
WSManStackVersionWSManStackVersion WS-Management 堆栈的版本号The version number of the WS-Management stack

$PWD$PWD

包含表示当前目录的完整路径的路径对象。Contains a path object that represents the full path of the current directory.

$Sender$Sender

包含生成此事件的对象。Contains the object that generated this event. 此变量仅在事件注册命令的操作块中进行填充。This variable is populated only within the Action block of an event registration command. 此变量的值还可在返回的 PSEventArgs 对象的发送方属性中找到 Get-EventThe value of this variable can also be found in the Sender property of the PSEventArgs object that Get-Event returns.

$ShellId$ShellId

包含当前 shell 的标识符。Contains the identifier of the current shell.

$StackTrace$StackTrace

包含最新错误的堆栈跟踪。Contains a stack trace for the most recent error.

$switch$switch

包含枚举器,而不包含语句的结果值 SwitchContains the enumerator not the resulting values of a Switch statement. $switch仅当语句正在运行时,才存在该变量 Switch ; 当语句完成执行时,该变量会被删除 switchThe $switch variable exists only while the Switch statement is running; it's deleted when the switch statement completes execution. 有关详细信息,请参阅 about_SwitchFor more information, see about_Switch.

枚举器包含可用于检索循环值和更改当前循环迭代的属性和方法。Enumerators contain properties and methods you can use to retrieve loop values and change the current loop iteration. 有关详细信息,请参阅 使用枚举器。For more information, see Using Enumerators.

$this$this

在定义脚本属性或脚本方法的脚本块中, $this 变量引用要扩展的对象。In a script block that defines a script property or script method, the $this variable refers to the object that is being extended.

在自定义类中, $this 变量引用类对象本身,以允许访问类中定义的属性和方法。In a custom class, the $this variable refers to the class object itself allowing access to properties and methods defined in the class.

$true$true

包含 TrueContains True. 可以在命令和脚本中使用此变量来表示 TrueYou can use this variable to represent True in commands and scripts.

使用枚举器Using Enumerators

$input$foreach$switch 变量是所有枚举器,用于循环访问由其包含代码块处理的值。The $input, $foreach, and $switch variables are all enumerators used to iterate through the values processed by their containing code block.

枚举器包含可用于提前或重置迭代或检索迭代值的属性和方法。An enumerator contains properties and methods you can use to advance or reset iteration, or retrieve iteration values. 直接操作枚举器并不是最佳做法。Directly manipulating enumerators isn't considered best practice.

  • 在循环中,应首选流控制关键字 " 中断继续 "。Within loops, flow control keywords break and continue should be preferred.

  • 在接受管道输入的函数中,最佳做法是将参数与 ValueFromPipelineValueFromPipelineByPropertyName 属性结合使用。Within functions that accept pipeline input, it's best practice to use Parameters with the ValueFromPipeline or ValueFromPipelineByPropertyName attributes.

    有关详细信息,请参阅 about_Functions_Advanced_ParametersFor more information, see about_Functions_Advanced_Parameters.

MoveNextMoveNext

MoveNext方法将枚举器推进到集合的下一个元素。The MoveNext method advances the enumerator to the next element of the collection. 如果枚举器已成功进行高级,则 MoveNext 返回 True ; 如果枚举数已越过集合的末尾,则返回 FalseMoveNext returns True if the enumerator was successfully advanced, False if the enumerator has passed the end of the collection.

备注

返回的 布尔 值会将我的 MoveNext 发送到输出流。The Boolean value returned my MoveNext is sent to the output stream. 可以通过将输出 typecasting 为 [void] 或将其传送到 Out-Null来禁止输出。You can suppress the output by typecasting it to [void] or piping it to Out-Null.

$input.MoveNext() | Out-Null
[void]$input.MoveNext()

重置Reset

Reset方法将枚举器设置为其初始位置,该位置位于集合中第一个元素 之前The Reset method sets the enumerator to its initial position, which is before the first element in the collection.

当前Current

当前属性获取集合中的元素或管道中的枚举器的当前位置。The Current property gets the element in the collection, or pipeline, at the current position of the enumerator.

当前 属性将继续返回相同的属性,直到调用 MoveNextThe Current property continues to return the same property until MoveNext is called.

示例Examples

示例1:使用 $input 变量Example 1: Using the $input variable

在下面的示例中,访问 $input 变量将清除变量,直到下一次执行进程块。In the following example, accessing the $input variable clears the variable until the next time the process block executes. 使用 Reset 方法会将变量重置 $input 为当前管道值。Using the Reset method resets the $input variable to the current pipeline value.

function Test
{
    begin
    {
        $i = 0
    }

    process
    {
        "Iteration: $i"
        $i++
        "`tInput: $input"
        "`tAccess Again: $input"
        $input.Reset()
        "`tAfter Reset: $input"
    }
}

"one","two" | Test
Iteration: 0
    Input: one
    Access Again:
    After Reset: one
Iteration: 1
    Input: two
    Access Again:
    After Reset: two

即使不访问变量,进程块也会自动推进该 $input 变量。The process block automatically advances the $input variable even if you don't access it.

$skip = $true
function Skip
{
    begin
    {
        $i = 0
    }

    process
    {
        "Iteration: $i"
        $i++
        if ($skip)
        {
            "`tSkipping"
            $skip = $false
        }
        else
        {
            "`tInput: $input"
        }
    }
}

"one","two" | Skip
Iteration: 0
    Skipping
Iteration: 1
    Input: two

示例2:在进程块外使用 $inputExample 2: Using $input outside the process block

在进程块外,该 $input 变量表示通过管道传递到函数中的所有值。Outside of the process block the $input variable represents all the values piped into the function.

  • 访问 $input 变量将清除所有值。Accessing the $input variable clears all values.
  • Reset 方法重置整个集合。The Reset method resets the entire collection.
  • 从未填充 当前 属性。The Current property is never populated.
  • MoveNext 方法返回 false,因为集合不能为高级。The MoveNext method returns false because the collection can't be advanced.
    • 调用 MoveNext 会清除该 $input 变量。Calling MoveNext clears out the $input variable.
Function All
{
    "All Values: $input"
    "Access Again: $input"
    $input.Reset()
    "After Reset: $input"
    $input.MoveNext() | Out-Null
    "After MoveNext: $input"
}

"one","two","three" | All
All Values: one two three
Access Again:
After Reset: one two three
After MoveNext:

示例3:使用 $input。当前属性Example 3: Using the $input.Current property

通过使用 当前 属性,可以多次访问当前管道值,而无需使用 Reset 方法。By using the Current property, the current pipeline value can be accessed multiple times without using the Reset method. 进程块不会自动调用 MoveNext 方法。The process block doesn't automatically call the MoveNext method.

除非显式调用 MoveNext,否则不会填充 当前 属性。The Current property will never be populated unless you explicitly call MoveNext. 当前 属性可以在进程块内多次访问,而无需清除其值。The Current property can be accessed multiple times inside the process block without clearing its value.

function Current
{
    begin
    {
        $i = 0
    }

    process
    {
        "Iteration: $i"
        $i++
        "`tBefore MoveNext: $($input.Current)"
        $input.MoveNext() | Out-Null
        "`tAfter MoveNext: $($input.Current)"
        "`tAccess Again: $($input.Current)"
    }
}

"one","two" | Current
Iteration: 0
    Before MoveNext:
    After MoveNext: one
    Access Again: one
Iteration: 1
    Before MoveNext:
    After MoveNext: two
    Access Again: two

示例4:使用 $foreach 变量Example 4: Using the $foreach variable

$input 变量不同,在 $foreach 直接访问时,变量始终表示集合中的所有项。Unlike the $input variable, the $foreach variable always represents all items in the collection when accessed directly. 使用 current 属性可以访问当前集合元素,使用 ResetMoveNext 方法可以更改其值。Use the Current property to access the current collection element, and the Reset and MoveNext methods to change its value.

备注

循环的每次迭代 foreach 都将自动调用 MoveNext 方法。Each iteration of the foreach loop will automatically call the MoveNext method.

以下循环只执行两次。The following loop only executes twice. 在第二次迭代中,在迭代完成之前,将集合移动到第三个元素。In the second iteration, the collection is moved to the third element before the iteration is complete. 在第二次迭代后,现在没有更多值可供迭代,循环将终止。After the second iteration, there are now no more values to iterate, and the loop terminates.

MoveNext 属性不影响所选择的用于循环访问集合的变量 ($Num) 。The MoveNext property doesn't affect the variable chosen to iterate through the collection ($Num).

$i = 0
foreach ($num in ("one","two","three"))
{
    "Iteration: $i"
    $i++
    "`tNum: $num"
    "`tCurrent: $($foreach.Current)"

    if ($foreach.Current -eq "two")
    {
        "Before MoveNext (Current): $($foreach.Current)"
        $foreach.MoveNext() | Out-Null
        "After MoveNext (Current): $($foreach.Current)"
        "Num has not changed: $num"
    }
}
Iteration: 0
        Num: one
        Current: one
Iteration: 1
        Num: two
        Current: two
Before MoveNext (Current): two
After MoveNext (Current): three
Num has not changed: two

使用 Reset 方法重置集合中的当前元素。Using the Reset method resets the current element in the collection. 下面的示例循环遍历前两个元素 两次 ,因为调用 Reset 方法。The following example loops through the first two elements twice because the Reset method is called. 在前两个循环之后, if 语句将失败,并且循环会正常地循环访问所有三个元素。After the first two loops, the if statement fails and the loop iterates through all three elements normally.

重要

这可能会导致无限循环。This could result in an infinite loop.

$stopLoop = 0
foreach ($num in ("one","two", "three"))
{
    ("`t" * $stopLoop) + "Current: $($foreach.Current)"

    if ($num -eq "two" -and $stopLoop -lt 2)
    {
        $foreach.Reset() | Out-Null
        ("`t" * $stopLoop) + "Reset Loop: $stopLoop"
        $stopLoop++
    }
}
Current: one
Current: two
Reset Loop: 0
        Current: one
        Current: two
        Reset Loop: 1
                Current: one
                Current: two
                Current: three

示例5:使用 $switch 变量Example 5: Using the $switch variable

$switch变量与变量具有完全相同的规则 $foreachThe $switch variable has the exact same rules as the $foreach variable. 下面的示例演示了所有枚举器概念。The following example demonstrates all the enumerator concepts.

备注

请注意, 即使在 break MoveNext 方法后面没有语句,也不会执行 NotEvaluated 事例。Note how the NotEvaluated case is never executed, even though there's no break statement after the MoveNext method.

$values = "Start", "MoveNext", "NotEvaluated", "Reset", "End"
$stopInfinite = $false
switch ($values)
{
    "MoveNext" {
        "`tMoveNext"
        $switch.MoveNext() | Out-Null
        "`tAfter MoveNext: $($switch.Current)"
    }
    # This case is never evaluated.
    "NotEvaluated" {
        "`tAfterMoveNext: $($switch.Current)"
    }

    "Reset" {
        if (!$stopInfinite)
        {
            "`tReset"
            $switch.Reset()
            $stopInfinite = $true
        }
    }

    default {
        "Default (Current): $($switch.Current)"
    }
}
Default (Current): Start
    MoveNext
    After MoveNext: NotEvaluated
    Reset
Default (Current): Start
    MoveNext
    After MoveNext: NotEvaluated
Default (Current): End

另请参阅See also

about_Functionsabout_Functions

about_Functions_Advancedabout_Functions_Advanced

about_Functions_Advanced_Methodsabout_Functions_Advanced_Methods

about_Functions_Advanced_Parametersabout_Functions_Advanced_Parameters

about_Functions_OutputTypeAttributeabout_Functions_OutputTypeAttribute

about_Functions_CmdletBindingAttributeabout_Functions_CmdletBindingAttribute

about_Hash_Tablesabout_Hash_Tables

about_Preference_Variablesabout_Preference_Variables

about_Splattingabout_Splatting

about_Variablesabout_Variables