关于首选项变量About Preference Variables

简短说明Short description

自定义 PowerShell 行为的变量。Variables that customize the behavior of PowerShell.

长说明Long description

PowerShell 包含一组变量,使你能够自定义其行为。PowerShell includes a set of variables that enable you to customize its behavior. 这些首选项变量的工作方式类似于基于 GUI 的系统中的选项。These preference variables work like the options in GUI-based systems.

首选项变量将影响 PowerShell 操作环境以及在环境中运行的所有命令。The preference variables affect the PowerShell operating environment and all commands run in the environment. 在许多情况下,cmdlet 具有可用于覆盖特定命令的首选项行为的参数。In many cases, the cmdlets have parameters that you can use to override the preference behavior for a specific command.

下表列出了首选项变量及其默认值。The following table lists the preference variables and their default values.

变量Variable 默认值Default Value
$ConfirmPreference High
$DebugPreference SilentlyContinueSilentlyContinue
$ErrorActionPreference 继续Continue
$ErrorView ConciseViewConciseView
$FormatEnumerationLimit 44
$InformationPreference SilentlyContinueSilentlyContinue
$LogCommandHealthEvent 错误 (未记录) False (not logged)
$LogCommandLifecycleEvent 错误 (未记录) False (not logged)
$LogEngineHealthEvent (记录为 True) True (logged)
$LogEngineLifecycleEvent (记录为 True) True (logged)
$LogProviderLifecycleEvent (记录为 True) True (logged)
$LogProviderHealthEvent (记录为 True) True (logged)
$MaximumHistoryCount 40964096
$OFS (空格字符 (" ") # A3(Space character (" "))
$OutputEncoding UTF8Encoding 对象UTF8Encoding object
$ProgressPreference 继续Continue
$PSDefaultParameterValues (无-) 哈希表(None - empty hash table)
$PSEmailServer (无)(None)
$PSModuleAutoLoadingPreference 全部All
$PSSessionApplicationName wsmanwsman
$PSSessionConfigurationName http://schemas.microsoft.com/powershell/Microsoft.PowerShell
$PSSessionOption 请参阅 $PSSessionOptionSee $PSSessionOption
$Transcript (无)(none)
$VerbosePreference SilentlyContinueSilentlyContinue
$WarningPreference 继续Continue
$WhatIfPreference FalseFalse

PowerShell 包括存储用户首选项的以下环境变量。PowerShell includes the following environment variables that store user preferences. 有关这些环境变量的详细信息,请参阅 about_Environment_VariablesFor more information about these environment variables, see about_Environment_Variables.

  • env:PSExecutionPolicyPreference
  • $env:PSModulePath

备注

首选项变量的更改仅对脚本和函数有效,前提是这些脚本或函数是在使用首选项的作用域中定义的。Changes to preference variable only take effect in scripts and functions if those scripts or functions are defined in the same scope as the scope in which preference was used. 有关详细信息,请参阅 about_ScopesFor more information, see about_Scopes.

使用首选项变量Working with preference variables

本文档介绍每个首选项变量。This document describes each of the preference variables.

若要显示特定首选项变量的当前值,请键入该变量的名称。To display the current value of a specific preference variable, type the variable's name. 例如,下面的命令显示 $ConfirmPreference 变量的值。For example, the following command displays the $ConfirmPreference variable's value.

 $ConfirmPreference
High

若要更改变量的值,请使用赋值语句。To change a variable's value, use an assignment statement. 例如,下面的语句将 $ConfirmPreference 参数的值更改为 " "。For example, the following statement changes the $ConfirmPreference parameter's value to Medium .

$ConfirmPreference = "Medium"

您设置的值特定于当前 PowerShell 会话。The values that you set are specific to the current PowerShell session. 若要使变量在所有 PowerShell 会话中生效,请将它们添加到 PowerShell 配置文件中。To make variables effective in all PowerShell sessions, add them to your PowerShell profile. 有关详细信息,请参阅 about_ProfilesFor more information, see about_Profiles.

远程工作Working remotely

在远程计算机上运行命令时,远程命令仅服从远程计算机的 PowerShell 客户端中的首选项设置。When you run commands on a remote computer, the remote commands are only subject to the preferences set in the remote computer's PowerShell client. 例如,当你运行远程命令时,远程计算机的变量的值将 $DebugPreference 决定 PowerShell 对调试消息的响应方式。For example, when you run a remote command, the value of the remote computer's $DebugPreference variable determines how PowerShell responds to debugging messages.

有关远程命令的详细信息,请参阅 about_RemoteFor more information about remote commands, see about_Remote.

$ConfirmPreference$ConfirmPreference

确定在运行 cmdlet 或函数之前 PowerShell 是否自动提示你进行确认。Determines whether PowerShell automatically prompts you for confirmation before running a cmdlet or function.

$ConfirmPreference变量的有效值为 " "、" " 或 " "。The $ConfirmPreference variable's valid values are High , Medium , or Low . 为 cmdlet 和函数分配了 的风险。Cmdlets and functions are assigned a risk of High , Medium , or Low . 当变量的值 $ConfirmPreference 小于或等于分配给 cmdlet 或函数的风险时,PowerShell 会在运行 cmdlet 或函数之前自动提示你进行确认。When the value of the $ConfirmPreference variable is less than or equal to the risk assigned to a cmdlet or function, PowerShell automatically prompts you for confirmation before running the cmdlet or function.

如果该变量的值 $ConfirmPreference 为 " ",则在运行 cmdlet 或函数之前,PowerShell 从不会自动提示您。If the value of the $ConfirmPreference variable is None , PowerShell never automatically prompts you before running a cmdlet or function.

若要更改会话中所有 cmdlet 和函数的确认行为,请更改 $ConfirmPreference 变量的值。To change the confirming behavior for all cmdlets and functions in the session, change $ConfirmPreference variable's value.

若要为 $ConfirmPreference 单个命令重写,请使用 cmdlet 或函数的 Confirm 参数。To override the $ConfirmPreference for a single command, use a cmdlet's or function's Confirm parameter. 若要请求确认,请使用 -ConfirmTo request confirmation, use -Confirm. 若要取消确认,请使用 -Confirm:$falseTo suppress confirmation, use -Confirm:$false.

有效值为 $ConfirmPreferenceValid values of $ConfirmPreference:

  • :不自动提示 PowerShell。None : PowerShell doesn't prompt automatically. 若要请求确认特定命令,请使用 cmdlet 或函数的 Confirm 参数。To request confirmation of a particular command, use the Confirm parameter of the cmdlet or function.
  • :在运行具有低、中或高风险的 cmdlet 或函数之前,PowerShell 会提示进行确认。Low : PowerShell prompts for confirmation before running cmdlets or functions with a low, medium, or high risk.
  • : PowerShell 在运行 cmdlet 之前提示进行确认,或使用中等或高风险运行这些功能。Medium : PowerShell prompts for confirmation before running cmdlets or functions with a medium, or high risk.
  • : PowerShell 在运行 cmdlet 或具有高风险的功能之前提示确认。High : PowerShell prompts for confirmation before running cmdlets or functions with a high risk.

详细说明Detailed explanation

PowerShell 可以在执行操作之前自动提示你进行确认。PowerShell can automatically prompt you for confirmation before doing an action. 例如,当 cmdlet 或函数严重影响系统以删除数据或使用大量系统资源时。For example, when cmdlet or function significantly affects the system to delete data or use a significant amount of system resources.

Remove-Item -Path C:\file.txt
Confirm
Are you sure you want to perform this action?
Performing operation "Remove File" on Target "C:\file.txt".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [?] Help (default is "Y"):

风险的估计值是指作为其 ConfirmImpact 的 cmdlet 或函数的属性。The estimate of the risk is an attribute of the cmdlet or function known as its ConfirmImpact . 用户无法更改它。Users can't change it.

可能会给系统带来风险的 cmdlet 和函数具有 Confirm 参数,可用于请求或取消对单个命令的确认。Cmdlets and functions that might pose a risk to the system have a Confirm parameter that you can use to request or suppress confirmation for a single command.

由于大多数 cmdlet 和函数使用 默认的风险ConfirmImpact ,而默认值为 "高",因此 $ConfirmPreferenceHigh 少发生自动确认。Because most cmdlets and functions use the default risk value, ConfirmImpact , of Medium , and the default value of $ConfirmPreference is High , automatic confirmation rarely occurs. 但是,可以通过将的值更改为 "中" $ConfirmPreferenceMedium " " 来激活自动确认。However, you can activate automatic confirmation by changing the value of $ConfirmPreference to Medium or Low .

示例Examples

此示例显示 $ConfirmPreference 变量的默认值( )的效果。This example shows the effect of the $ConfirmPreference variable's default value, High . 值仅用于确认高风险 cmdlet 和函数。The High value only confirms high-risk cmdlets and functions. 由于大多数 cmdlet 和函数都是中等风险,因此它们不会自动确认并 Remove-Item 删除文件。Since most cmdlets and functions are medium risk, they aren't automatically confirmed and Remove-Item deletes the file. 添加 -Confirm 到命令会提示用户进行确认。Adding -Confirm to the command prompts the user for confirmation.

$ConfirmPreference
High
Remove-Item -Path C:\temp1.txt

使用 -Confirm 请求确认。Use -Confirm to request confirmation.

Remove-Item -Path C:\temp2.txt -Confirm
Confirm
Are you sure you want to perform this action?
Performing operation "Remove File" on Target "C:\temp2.txt".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All
[?] Help (default is "Y"):

下面的示例演示了将的值更改为 " $ConfirmPreference " 的效果。The following example shows the effect of changing the value of $ConfirmPreference to Medium . 由于大多数 cmdlet 和函数都是中等风险,因此它们会自动得到确认。Because most cmdlets and function are medium risk, they're automatically confirmed. 若要禁止显示单个命令的确认提示,请使用值为的 Confirm 参数 $falseTo suppress the confirmation prompt for a single command, use the Confirm parameter with a value of $false.

$ConfirmPreference = "Medium"
Remove-Item -Path C:\temp2.txt
Confirm
Are you sure you want to perform this action?
Performing operation "Remove File" on Target "C:\temp2.txt".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All
[?] Help (default is "Y"):
Remove-Item -Path C:\temp3.txt -Confirm:$false

$DebugPreference$DebugPreference

确定 PowerShell 如何响应脚本、cmdlet 或提供程序所生成的消息,或 Write-Debug 命令行中的命令。Determines how PowerShell responds to debugging messages generated by a script, cmdlet or provider, or by a Write-Debug command at the command line.

某些 cmdlet 显示调试消息,这些消息通常是为程序员和技术支持专业人员设计的技术消息。Some cmdlets display debugging messages, which are typically technical messages designed for programmers and technical support professionals. 默认情况下,调试消息不会显示,但你可以通过更改的值来显示调试消息 $DebugPreferenceBy default, debugging messages aren't displayed, but you can display debugging messages by changing the value of $DebugPreference.

可以使用 cmdlet 的 Debug 通用参数来显示或隐藏特定命令的调试消息。You can use the Debug common parameter of a cmdlet to display or hide the debugging messages for a specific command. 有关详细信息,请参阅 about_CommonParametersFor more information, see about_CommonParameters.

有效值如下:The valid values are as follows:

  • 停止 :显示调试消息,并停止执行。Stop : Displays the debug message and stops executing. 向控制台写入错误。Writes an error to the console.
  • Inquire :显示调试消息,并询问您是否要继续。Inquire : Displays the debug message and asks you whether you want to continue. Debug common 参数添加到命令时,在将该命令配置为生成调试消息时,将更改该变量的值 $DebugPreference 以进行 查询Adding the Debug common parameter to a command, when the command is configured to generate a debugging message, changes the value of the $DebugPreference variable to Inquire .
  • 继续 :显示调试消息,并继续执行。Continue : Displays the debug message and continues with execution.
  • SilentlyContinue : (默认值) 不起作用。SilentlyContinue : (Default) No effect. 调试消息不会显示,执行将继续进行而不中断。The debug message isn't displayed and execution continues without interruption.

示例Examples

下面的示例演示在 $DebugPreference 命令行中输入命令时更改值的影响 Write-DebugThe following examples show the effect of changing the values of $DebugPreference when a Write-Debug command is entered at the command line. 更改会影响所有调试消息,包括 cmdlet 和脚本生成的消息。The change affects all debugging messages, including messages generated by cmdlets and scripts. 示例显示了 Debug 参数,该参数显示或隐藏与单个命令相关的调试消息。The examples show the Debug parameter, which displays or hides the debugging messages related to a single command.

此示例显示 $DebugPreference 变量的默认值 SilentlyContinue 的效果。This example shows the effect of the $DebugPreference variable's default value, SilentlyContinue . 默认情况下, Write-Debug cmdlet 的调试消息不会显示并且处理将继续进行。By default, the Write-Debug cmdlet's debug message isn't displayed and processing continues. 使用 Debug 参数时,它将覆盖单个命令的首选项。When the Debug parameter is used, it overrides the preference for a single command. 将显示调试消息。The debug message is displayed.

$DebugPreference
SilentlyContinue
Write-Debug -Message "Hello, World"
Write-Debug -Message "Hello, World" -Debug
DEBUG: Hello, World

此示例显示了 $DebugPreference 具有 Continue 值的效果。This example shows the effect of $DebugPreference with the Continue value. 调试消息随即显示,命令继续处理。The debug message is displayed and the command continues to process.

$DebugPreference = "Continue"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World

此示例使用 Debug 参数,其中的值 $false 为,以禁止将消息用于单个命令。This example uses the Debug parameter with a value of $false to suppress the message for a single command. 不显示调试消息。The debug message isn't displayed.

Write-Debug -Message "Hello, World" -Debug:$false

此示例显示 $DebugPreference 设置为 " 停止 " 值的效果。This example shows the effect of $DebugPreference being set to the Stop value. 将显示调试消息,并停止该命令。The debug message is displayed and the command is stopped.

$DebugPreference = "Stop"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World
Write-Debug : The running command stopped because the preference variable
 "DebugPreference" or common parameter is set to Stop: Hello, World
At line:1 char:1
+ Write-Debug -Message "Hello, World"

此示例使用 Debug 参数,其中的值 $false 为,以禁止将消息用于单个命令。This example uses the Debug parameter with a value of $false to suppress the message for a single command. 调试消息不会显示并且不会停止处理。The debug message isn't displayed and processing isn't stopped.

Write-Debug -Message "Hello, World" -Debug:$false

此示例显示了 $DebugPreference 设置为 查询 值的效果。This example shows the effect of $DebugPreference being set to the Inquire value. 将显示调试消息,并提示用户进行确认。The debug message is displayed and the user is prompted for confirmation.

$DebugPreference = "Inquire"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [?] Help (default is "Y"):

此示例使用 Debug 参数,其中的值 $false 为,以禁止将消息用于单个命令。This example uses the Debug parameter with a value of $false to suppress the message for a single command. 调试消息不会显示并继续处理。The debug message isn't displayed and processing continues.

Write-Debug -Message "Hello, World" -Debug:$false

$ErrorActionPreference$ErrorActionPreference

确定 PowerShell 如何响应非终止错误,该错误不会停止 cmdlet 处理。Determines how PowerShell responds to a non-terminating error, an error that doesn't stop the cmdlet processing. 例如,在命令行或脚本、cmdlet 或提供程序中,如 cmdlet 生成的错误 Write-ErrorFor example, at the command line or in a script, cmdlet, or provider, such as the errors generated by the Write-Error cmdlet.

可以使用 cmdlet 的 ErrorAction 通用参数来覆盖特定命令的首选项。You can use a cmdlet's ErrorAction common parameter to override the preference for a specific command.

有效值如下:The valid values are as follows:

  • Break -在发生错误或引发异常时输入调试器。Break - Enter the debugger when an error occurs or when an exception is raised.
  • 继续 : (默认值) 显示错误消息并继续执行。Continue : (Default) Displays the error message and continues executing.
  • Ignore :禁止显示错误消息并继续执行命令。Ignore : Suppresses the error message and continues to execute the command. Ignore 值专用于按命令使用,而不是用作保存的首选项。The Ignore value is intended for per-command use, not for use as saved preference. Ignore 不是变量的有效值 $ErrorActionPreferenceIgnore isn't a valid value for the $ErrorActionPreference variable.
  • Inquire :显示错误消息,并询问您是否要继续。Inquire : Displays the error message and asks you whether you want to continue.
  • SilentlyContinue :不起作用。SilentlyContinue : No effect. 错误消息不会显示,执行将继续进行而不中断。The error message isn't displayed and execution continues without interruption.
  • 停止 :显示错误消息并停止执行。Stop : Displays the error message and stops executing. 除生成的错误外, 停止 值还会将 ActionPreferenceStopException 对象生成到错误流。In addition to the error generated, the Stop value generates an ActionPreferenceStopException object to the error stream. 流 (stream)stream
  • 挂起 :自动挂起工作流作业以便进一步进行调查。Suspend : Automatically suspends a workflow job to allow for further investigation. 调查后,工作流可以恢复。After investigation, the workflow can be resumed. " 挂起 " 值适用于按命令使用,而不是用作保存的首选项。The Suspend value is intended for per-command use, not for use as saved preference. 挂起 不是变量的有效值 $ErrorActionPreferenceSuspend isn't a valid value for the $ErrorActionPreference variable.

$ErrorActionPreferenceErrorAction 参数不会影响 PowerShell 响应终止处理停止 cmdlet 的错误的方式。$ErrorActionPreference and the ErrorAction parameter don't affect how PowerShell responds to terminating errors that stop cmdlet processing. 有关 ErrorAction 通用参数的详细信息,请参阅 about_CommonParametersFor more information about the ErrorAction common parameter, see about_CommonParameters.

示例Examples

这些示例显示变量的不同值的影响 $ErrorActionPreferenceThese examples show the effect of the different values of the $ErrorActionPreference variable. ErrorAction 参数用于重写 $ErrorActionPreference 值。The ErrorAction parameter is used to override the $ErrorActionPreference value.

此示例显示 $ErrorActionPreference 默认值 " Continue "。This example shows the $ErrorActionPreference default value, Continue . 生成非终止错误。A non-terminating error is generated. 消息随即显示并且处理继续。The message is displayed and processing continues.

# Change the ErrorActionPreference to 'Continue'
$ErrorActionPreference = 'Continue'
# Generate a non-terminating error and continue processing the script.
Write-Error -Message  'Test Error' ; Write-Host 'Hello World'
Write-Error: Test Error
Hello World

此示例显示 $ErrorActionPreference 默认值 InquireThis example shows the $ErrorActionPreference default value, Inquire . 将生成一个错误,并显示一个操作提示。An error is generated and a prompt for action is shown.

# Change the ErrorActionPreference to 'Inquire'
$ErrorActionPreference = 'Inquire'
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
Confirm
Test Error
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

此示例显示 $ErrorActionPreference 设置为 SilentlyContinueThis example shows the $ErrorActionPreference set to SilentlyContinue . 错误消息将被取消。The error message is suppressed.

# Change the ErrorActionPreference to 'SilentlyContinue'
$ErrorActionPreference = 'SilentlyContinue'
# Generate an error message
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
# Error message is suppressed and script continues processing
Hello World

此示例显示 $ErrorActionPreference 设置为 " 停止 "。This example shows the $ErrorActionPreference set to Stop . 它还显示生成到变量的额外对象 $ErrorIt also shows the extra object generated to the $Error variable.

# Change the ErrorActionPreference to 'Stop'
$ErrorActionPreference = 'Stop'
# Error message is is generated and script stops processing
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'

# Show the ActionPreferenceStopException and the error generated
$Error[0]
$Error[1]
Write-Error: Test Error

ErrorRecord                 : Test Error
WasThrownFromThrowStatement : False
TargetSite                  : System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]
                              Invoke(System.Collections.IEnumerable)
StackTrace                  :    at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
                                 at Microsoft.PowerShell.Executor.ExecuteCommandHelper(Pipeline tempPipeline,
                              Exception& exceptionThrown, ExecutionOptions options)
Message                     : The running command stopped because the preference variable "ErrorActionPreference" or
                              common parameter is set to Stop: Test Error
Data                        : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException              :
HelpLink                    :
Source                      : System.Management.Automation
HResult                     : -2146233087

Write-Error: Test Error

$ErrorView$ErrorView

确定 PowerShell 中错误消息的显示格式。Determines the display format of error messages in PowerShell.

有效值如下:The valid values are as follows:

  • ConciseView : (默认值) 提供简洁的错误消息和高级模块生成器的重构视图。ConciseView : (Default) Provides a concise error message and a refactored view for advanced module builders. 如果错误来自命令行,则为单行错误消息。If the error is from command line it's a single line error message. 否则,你将收到一条多行错误消息,其中包含错误和指向错误显示在该行中出现位置的错误。Otherwise, you receive a multiline error message that contains the error and a pointer to the error showing where it occurs in that line. 如果终端支持虚拟终端,则使用 ANSI 颜色代码提供颜色着色。If the terminal supports Virtual Terminal, then ANSI color codes are used to provide color accent. 可以在处更改强调颜色 $Host.PrivateData.ErrorAccentColorThe Accent color can be changed at $Host.PrivateData.ErrorAccentColor. 使用 Get-Error cmdlet 提供完全限定的错误的综合性详细视图,包括内部异常。Use Get-Error cmdlet for a comprehensive detailed view of the fully qualified error, including inner exceptions.

    PowerShell 7 中添加了 ConciseViewConciseView was added in PowerShell 7.

  • NormalView :为大多数用户设计的详细视图。NormalView : A detailed view designed for most users. 包含错误说明和错误中涉及的对象的名称。Consists of a description of the error and the name of the object involved in the error.

  • CategoryView :一种简洁的结构化视图,适用于生产环境。CategoryView : A succinct, structured view designed for production environments. 其格式如下所示:The format is as follows:

    {Category}: ( {TargetName}: {TargetType} ) : [{Activity}],{Reason}{Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}

有关 CategoryView 中的字段的详细信息,请参阅 ErrorCategoryInfo 类。For more information about the fields in CategoryView , see ErrorCategoryInfo class.

示例Examples

此示例演示当的值 $ErrorView 为默认值 ConciseView 时,如何显示错误。This example shows how an error appears when the value of $ErrorView is the default, ConciseView . Get-ChildItem 用于查找不存在的目录。Get-ChildItem is used to find a non-existent directory.

Get-ChildItem -path 'C:\NoRealDirectory'
Get-ChildItem: Cannot find path 'C:\NoRealDirectory' because it does not exist.

此示例演示当的值 $ErrorView 为默认值 ConciseView 时,如何显示错误。This example shows how an error appears when the value of $ErrorView is the default, ConciseView . Script.ps1 运行,并引发语句中的错误 Get-ItemScript.ps1 is run and throws an error from Get-Item statement.

./Script.ps1
Get-Item: C:\Script.ps1
Line |
  11 | Get-Item -Path .\stuff
     | ^ Cannot find path 'C:\demo\stuff' because it does not exist.

此示例演示如何在的值 $ErrorView 更改为 NormalView 时显示错误。This example shows how an error appears when the value of $ErrorView is changed to NormalView . Get-ChildItem 用于查找不存在的文件。Get-ChildItem is used to find a non-existent file.

Get-ChildItem -Path C:\nofile.txt
Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path C:\nofile.txt

此示例演示当的值 $ErrorView 更改为 CategoryView 时出现的相同错误。This example shows how the same error appears when the value of $ErrorView is changed to CategoryView .

$ErrorView = "CategoryView"
Get-ChildItem -Path C:\nofile.txt
ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException

此示例演示的值 $ErrorView 仅影响错误显示。This example demonstrates that the value of $ErrorView only affects the error display. 它不会更改自动变量中存储的错误对象的结构 $ErrorIt doesn't change the structure of the error object that is stored in the $Error automatic variable. 有关 $Error 自动变量的信息,请参阅 about_automatic_variablesFor information about the $Error automatic variable, see about_automatic_variables.

下面的命令使用与错误数组中的最新错误( 元素 0 )关联的 ErrorRecord 对象,并在列表中设置所有错误对象属性的格式。The following command takes the ErrorRecord object associated with the most recent error in the error array, element 0 , and formats all the error object's properties in a list.

$Error[0] | Format-List -Property * -Force
PSMessageDetails      :
Exception             : System.Management.Automation.ItemNotFoundException:
                          Cannot find path 'C:\nofile.txt' because it does
                          not exist.
                        at System.Management.Automation.SessionStateInternal.
                          GetChildItems(String path, Boolean recurse, UInt32
                          depth, CmdletProviderContext context)
                        at System.Management.Automation.ChildItemCmdlet
                          ProviderIntrinsics.Get(String path, Boolean
                          recurse, UInt32 depth, CmdletProviderContext context)
                        at Microsoft.PowerShell.Commands.GetChildItemCommand.
                          ProcessRecord()
TargetObject          : C:\nofile.txt
CategoryInfo          : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem],
                          ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,
                          Microsoft.PowerShell.Commands.GetChildItemCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {0, 1}

$FormatEnumerationLimit$FormatEnumerationLimit

确定显示中包含多少个枚举项。Determines how many enumerated items are included in a display. 此变量不影响基础对象,仅影响显示。This variable doesn't affect the underlying objects, only the display. 如果的值 $FormatEnumerationLimit 小于枚举项的数目,则 PowerShell 会添加一个省略号 (...) 以指示未显示的项。When the value of $FormatEnumerationLimit is fewer than the number of enumerated items, PowerShell adds an ellipsis (...) to indicate items not shown.

有效值 :整数 (Int32) Valid values : Integers (Int32)

默认值 :4Default value : 4

示例Examples

此示例演示如何使用 $FormatEnumerationLimit 变量来改善枚举项的显示。This example shows how to use the $FormatEnumerationLimit variable to improve the display of enumerated items.

此示例中的命令将生成一个表,该表列出了在计算机上运行的所有服务,一个用于 运行 服务,另一个用于 已停止 的服务。The command in this example generates a table that lists all the services running on the computer in two groups: one for running services and one for stopped services. 它使用 Get-Service 命令获取所有服务,然后将结果通过管道发送到 Group-Object cmdlet,后者按服务状态对结果进行分组。It uses a Get-Service command to get all the services, and then sends the results through the pipeline to the Group-Object cmdlet, which groups the results by the service status.

结果是一个表,其中列出了 " 名称 " 列中的状态和 " " 列中的进程。The result is a table that lists the status in the Name column, and the processes in the Group column. 若要更改列标签,请使用哈希表,请参阅 about_Hash_TablesTo change the column labels, use a hash table, see about_Hash_Tables. 有关详细信息,请参阅 格式表中的示例。For more information, see the examples in Format-Table.

查找的当前值 $FormatEnumerationLimitFind the current value of $FormatEnumerationLimit.

$FormatEnumerationLimit
4

列出按 状态 分组的所有服务。List all services grouped by Status . 每个状态的 " " 列中最多列出了四个服务,因为 $FormatEnumerationLimit 值为 4There are a maximum of four services listed in the Group column for each status because $FormatEnumerationLimit has a value of 4 .

Get-Service | Group-Object -Property Status
Count  Name       Group
-----  ----       -----
60     Running    {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...}
41     Stopped    {Alerter, AppMgmt, aspnet_state, ATI Smart...}

若要增加列出的项数,请将的值增加 $FormatEnumerationLimit1000To increase the number of items listed, increase the value of $FormatEnumerationLimit to 1000 . 使用 Get-ServiceGroup-Object 显示服务。Use Get-Service and Group-Object to display the services.

$FormatEnumerationLimit = 1000
Get-Service | Group-Object -Property Status
Count  Name       Group
-----  ----       -----
60     Running    {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec...
41     Stopped    {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc...

Format-TableWrap 参数一起使用以显示服务列表。Use Format-Table with the Wrap parameter to display the list of services.

Get-Service | Group-Object -Property Status | Format-Table -Wrap
Count  Name       Group
-----  ----       -----
60     Running    {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec,
                  Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver,
                  Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc,
                  HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver,
                  lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla,
                  NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan,
                  RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS,
                  SharedAccess, ShellHWDetection, SMT PSVC, Spooler,
                  srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes,
                  TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc,
                  wuauserv, WZCSVC, zzInterix}

41     Stopped    {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc,
                  ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp,
                  CronService, dmadmin, FastUserSwitchingCompatibility,
                  HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc,
                  MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc,
                  NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator,
                  SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS,
                  WmdmPmSN, Wmi, WmiApSrv, xmlprov}

$InformationPreference$InformationPreference

$InformationPreference利用变量,可以设置要向用户显示的信息流首选项。The $InformationPreference variable lets you set information stream preferences that you want displayed to users. 具体而言,是通过添加 写入信息 cmdlet 添加到命令或脚本的信息性消息。Specifically, informational messages that you added to commands or scripts by adding the Write-Information cmdlet. 如果使用 InformationAction 参数,则其值将覆盖变量的值 $InformationPreferenceIf the InformationAction parameter is used, its value overrides the value of the $InformationPreference variable. Write-Information 是在 PowerShell 5.0 中引入的。Write-Information was introduced in PowerShell 5.0.

有效值如下:The valid values are as follows:

  • Stop :在命令出现时停止命令或脚本 Write-InformationStop : Stops a command or script at an occurrence of the Write-Information command.
  • Inquire :显示你在命令中指定的信息性消息 Write-Information ,然后询问你是否要继续。Inquire : Displays the informational message that you specify in a Write-Information command, then asks whether you want to continue.
  • 继续 :显示信息性消息,并继续运行。Continue : Displays the informational message, and continues running.
  • " 挂起 " 仅适用于 PowerShell 6 和更高版本中不支持的工作流。Suspend is only available for workflows which aren't supported in PowerShell 6 and beyond.
  • SilentlyContinue : (默认值) 不起作用。SilentlyContinue : (Default) No effect. 不显示信息性消息,该脚本将继续进行而不中断。The informational messages aren't displayed, and the script continues without interruption.

$Log * 事件$Log*Event

日志 * 事件 首选项变量确定哪些类型的事件将写入事件查看器中的 PowerShell 事件日志。The Log*Event preference variables determine which types of events are written to the PowerShell event log in Event Viewer. 默认情况下,只记录引擎和提供程序事件。By default, only engine and provider events are logged. 但你可以使用 log * 事件 首选项变量来自定义日志,如记录有关命令的事件。But, you can use the Log*Event preference variables to customize your log, such as logging events about commands.

日志 * 事件 首选项变量如下所示:The Log*Event preference variables are as follows:

  • $LogCommandHealthEvent:记录命令初始化和处理中的错误和异常。$LogCommandHealthEvent: Logs errors and exceptions in command initialization and processing. 默认值为 $false (未记录) 。The default is $false (not logged).
  • $LogCommandLifecycleEvent:记录命令和命令管道的启动和停止,以及命令发现中的安全异常。$LogCommandLifecycleEvent: Logs the starting and stopping of commands and command pipelines and security exceptions in command discovery. 默认值为 $false (未记录) 。The default is $false (not logged).
  • $LogEngineHealthEvent:记录会话的错误和失败。$LogEngineHealthEvent: Logs errors and failures of sessions. 默认值为 $true (记录) 。The default is $true (logged).
  • $LogEngineLifecycleEvent:记录会话的开始和结束。$LogEngineLifecycleEvent: Logs the opening and closing of sessions. 默认值为 $true (记录) 。The default is $true (logged).
  • $LogProviderHealthEvent:记录提供程序错误,如读取和写入错误、查找错误以及调用错误。$LogProviderHealthEvent: Logs provider errors, such as read and write errors, lookup errors, and invocation errors. 默认值为 $true (记录) 。The default is $true (logged).
  • $LogProviderLifecycleEvent:日志添加和删除 PowerShell 提供程序。$LogProviderLifecycleEvent: Logs adding and removing of PowerShell providers. 默认值为 $true (记录) 。The default is $true (logged). 有关 PowerShell 提供程序的信息,请参阅 about_ProvidersFor information about PowerShell providers, see about_Providers.

若要启用 Log * 事件 ,请键入变量,其值 $true 为,例如:To enable a Log*Event , type the variable with a value of $true, for example:

$LogCommandLifeCycleEvent = $true

若要禁用事件类型,请使用值键入变量 $false ,例如:To disable an event type, type the variable with a value of $false, for example:

$LogCommandLifeCycleEvent = $false

启用的事件仅对当前 PowerShell 控制台有效。The events that you enable are effective only for the current PowerShell console. 若要将配置应用到所有控制台,请将变量设置保存到 PowerShell 配置文件中。To apply the configuration to all consoles, save the variable settings in your PowerShell profile. 有关详细信息,请参阅 about_ProfilesFor more information, see about_Profiles.

$MaximumHistoryCount$MaximumHistoryCount

确定在当前会话的命令历史记录中保存的命令数。Determines how many commands are saved in the command history for the current session.

有效值 : 1-32768 (Int32) Valid values : 1 - 32768 (Int32)

默认值 :4096Default : 4096

若要确定命令历史记录中当前保存的命令数,请键入:To determine the number of commands current saved in the command history, type:

(Get-History).Count

若要查看已保存在会话历史记录中的命令,请使用 Get-History cmdlet。To see the commands saved in your session history, use the Get-History cmdlet. 有关详细信息,请参阅 about_HistoryFor more information, see about_History.

$.OFS$OFS

(.OFS 的输出字段分隔符) 指定将转换为字符串的数组元素分隔的字符。The Output Field Separator (OFS) specifies the character that separates the elements of an array that is converted to a string.

有效值 :任何字符串。Valid values : Any string.

默认值 : SpaceDefault : Space

默认情况下,该 $OFS 变量不存在,并且输出文件分隔符为空格,但您可以添加此变量并将其设置为任何字符串。By default, the $OFS variable doesn't exist and the output file separator is a space, but you can add this variable and set it to any string. 可以 $OFS 通过键入在会话中更改的值 $OFS="<value>"You can change the value of $OFS in your session, by typing $OFS="<value>".

备注

如果需要在 " " 脚本、模块或配置输出中 () 的空间的默认值,请小心,不要在 $OFS 代码中的其他位置更改默认值。If you're expecting the default value of a space (" ") in your script, module, or configuration output, be careful that the $OFS default value hasn't been changed elsewhere in your code.

示例Examples

此示例显示当数组转换为字符串时,将使用空格来分隔值。This example shows that a space is used to separate the values when an array is converted to a string. 在这种情况下,整数数组存储在一个变量中,然后将该变量强制转换为字符串。In this case, an array of integers is stored in a variable and then the variable is cast as a string.

$array = 1,2,3,4
[string]$array
1 2 3 4

若要更改分隔符,请 $OFS 通过为变量赋值来添加变量。To change the separator, add the $OFS variable by assigning a value to it. 变量必须命名为 $OFSThe variable must be named $OFS.

$OFS = "+"
[string]$array
1+2+3+4

若要还原默认行为,可以 () 分配一个空格, " " $OFS 或删除该变量。To restore the default behavior, you can assign a space (" ") to the value of $OFS or delete the variable. 以下命令将删除该变量,然后验证该分隔符是否为空格。The following commands delete the variable and then verify that the separator is a space.

Remove-Variable OFS
[string]$array
1 2 3 4

$OutputEncoding$OutputEncoding

确定 PowerShell 在向其他应用程序发送文本时所使用的字符编码方法。Determines the character encoding method that PowerShell uses when it sends text to other applications.

例如,如果应用程序将 Unicode 字符串返回到 PowerShell,你可能需要将值更改为 UnicodeEncoding ,以便正确发送字符。For example, if an application returns Unicode strings to PowerShell, you might need to change the value to UnicodeEncoding to send the characters correctly.

有效值如下:派生自编码类的对象,例如 ASCIIEncodingSBCSCodePageEncodingUTF7EncodingUTF8EncodingUTF32EncodingUnicodeEncodingThe valid values are as follows: Objects derived from an Encoding class, such as ASCIIEncoding , SBCSCodePageEncoding , UTF7Encoding , UTF8Encoding , UTF32Encoding , and UnicodeEncoding .

默认值 : UTF8Encoding 对象 (UTF8Encoding) Default : UTF8Encoding object (System.Text.UTF8Encoding)

示例Examples

此示例演示如何在使用 Unicode 字符(如中文)为语言本地化的计算机上,使 Windows findstr.exe 命令在 PowerShell 中运行。This example shows how to make the Windows findstr.exe command work in PowerShell on a computer that is localized for a language that uses Unicode characters, such as Chinese.

第一个命令查找值 $OutputEncodingThe first command finds the value of $OutputEncoding. 由于值是编码对象,因此只显示其 encoding.encodingname 属性。Because the value is an encoding object, display only its EncodingName property.

$OutputEncoding.EncodingName

在此示例中, findstr.exe 命令用于搜索文件中存在的两个中文字符 Test.txtIn this example, a findstr.exe command is used to search for two Chinese characters that are present in the Test.txt file. 在 Windows 命令提示符下运行此 findstr.exe 命令时 ( cmd.exe ) , findstr.exe 将查找文本文件中的字符。When this findstr.exe command is run in the Windows Command Prompt ( cmd.exe ), findstr.exe finds the characters in the text file. 但是,当你在 PowerShell 中运行相同的 findstr.exe 命令时,将找不到这些字符,因为 PowerShell 会将它们发送到 ASCII 文本中的 findstr.exe 而不是 Unicode 文本。However, when you run the same findstr.exe command in PowerShell, the characters aren't found because the PowerShell sends them to findstr.exe in ASCII text, instead of in Unicode text.

findstr <Unicode-characters>

若要在 PowerShell 中运行命令,请将的值设置 $OutputEncoding 为控制台的 OutputEncoding 属性的值,该属性基于为 Windows 选择的区域设置。To make the command work in PowerShell, set the value of $OutputEncoding to the value of the OutputEncoding property of the console, that is based on the locale selected for Windows. 由于 OutputEncoding 是控制台的静态属性,因此请在命令中使用双冒号 (::) 。Because OutputEncoding is a static property of the console, use double-colons (::) in the command.

$OutputEncoding = [console]::OutputEncoding
$OutputEncoding.EncodingName
OEM United States

编码更改后, findstr.exe 命令将查找 Unicode 字符。After the encoding change, the findstr.exe command finds the Unicode characters.

findstr <Unicode-characters>
test.txt:         <Unicode-characters>

$ProgressPreference$ProgressPreference

确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的进度更新,如 写入-进度 cmdlet 生成的进度栏。Determines how PowerShell responds to progress updates generated by a script, cmdlet, or provider, such as the progress bars generated by the Write-Progress cmdlet. Write-ProgressCmdlet 可创建显示命令状态的进度栏。The Write-Progress cmdlet creates progress bars that show a command's status.

有效值如下:The valid values are as follows:

  • 停止 :不显示进度栏。Stop : Doesn't display the progress bar. 相反,它将显示一条错误消息并停止执行。Instead, it displays an error message and stops executing.
  • Inquire :不显示进度栏。Inquire : Doesn't display the progress bar. 提示继续操作。Prompts for permission to continue. 如果你通过 YA 进行回复,它会显示进度栏。If you reply with Y or A, it displays the progress bar.
  • 继续 : (默认值) 显示进度栏,并继续执行操作。Continue : (Default) Displays the progress bar and continues with execution.
  • SilentlyContinue :执行命令,但不显示进度栏。SilentlyContinue : Executes the command, but doesn't display the progress bar.

$PSEmailServer$PSEmailServer

指定用于发送电子邮件的默认电子邮件服务器。Specifies the default e-mail server that is used to send email messages. 发送电子邮件的 cmdlet (如 send-mailmessage cmdlet)使用此首选项变量。This preference variable is used by cmdlets that send email, such as the Send-MailMessage cmdlet.

$PSDefaultParameterValues$PSDefaultParameterValues

为 cmdlet 和高级函数的参数指定默认值。Specifies default values for the parameters of cmdlets and advanced functions. 的值 $PSDefaultParameterValues 是一个哈希表,其中的键由 cmdlet 名称和参数名称组成,该名称由冒号 (:) 分隔。The value of $PSDefaultParameterValues is a hash table where the key consists of the cmdlet name and parameter name separated by a colon (:). 值是指定的自定义默认值。The value is a custom default value that you specify.

$PSDefaultParameterValues 是在 PowerShell 3.0 中引入的。$PSDefaultParameterValues was introduced in PowerShell 3.0.

有关此首选项变量的详细信息,请参阅 about_Parameters_Default_ValuesFor more information about this preference variable, see about_Parameters_Default_Values.

$PSModuleAutoloadingPreference$PSModuleAutoloadingPreference

启用和禁用会话中模块的自动导入。Enables and disables automatic importing of modules in the session. All 为默认值。All is the default. 无论变量的值是什么,都可以使用 import-module 导入模块。Regardless of the variable's value, you can use Import-Module to import a module.

有效值是:Valid values are:

  • 所有 :首次使用时自动导入模块。All : Modules are imported automatically on first-use. 若要导入模块,请获取或使用模块中的任何命令。To import a module, get or use any command in the module. 例如,使用 Get-CommandFor example, use Get-Command.
  • ModuleQualified :仅当用户使用模块中的模块限定名称时,才会自动导入模块。ModuleQualified : Modules are imported automatically only when a user uses the module-qualified name of a command in the module. 例如,如果用户键入,则 MyModule\MyCommand PowerShell 将导入 MyModule 模块。For example, if the user types MyModule\MyCommand, PowerShell imports the MyModule module.
  • None :在会话中禁用自动导入模块。None : Automatic importing of modules is disabled in the session. 若要导入模块,请使用 Import-Module cmdlet。To import a module, use the Import-Module cmdlet.

有关自动导入模块的详细信息,请参阅 about_ModulesFor more information about automatic importing of modules, see about_Modules.

$PSSessionApplicationName$PSSessionApplicationName

指定远程命令的默认应用程序名称,该命令使用 (WS-MANAGEMENT) 技术管理的 "Web 服务"。Specifies the default application name for a remote command that uses Web Services for Management (WS-Management) technology. 有关详细信息,请参阅 关于 Windows 远程管理For more information, see About Windows Remote Management.

系统默认应用程序名称为 WSMAN ,但你可以使用此首选项变量更改默认值。The system default application name is WSMAN, but you can use this preference variable to change the default.

应用程序名称是连接 URI 中的最后一个节点。The application name is the last node in a connection URI. 例如,下面的示例 URI 中的应用程序名称为 WSMANFor example, the application name in the following sample URI is WSMAN.

http://Server01:8080/WSMAN

如果远程命令未指定连接 URI 或应用程序名称,则使用默认应用程序名称。The default application name is used when the remote command doesn't specify a connection URI or an application name.

WinRM 服务使用应用程序名称来选择用于处理连接请求的侦听器。The WinRM service uses the application name to select a listener to service the connection request. 参数的值应与远程计算机上的侦听器的 URLPrefix 属性值相匹配。The parameter's value should match the value of the URLPrefix property of a listener on the remote computer.

若要覆盖系统默认值和此变量的值,并为特定会话选择不同的应用程序名称,请使用 新的 PSSessionEnter-Pssession调用命令cmdlet 的 ConnectionURIApplicationName 参数。To override the system default and the value of this variable, and select a different application name for a particular session, use the ConnectionURI or ApplicationName parameters of the New-PSSession, Enter-PSSession, or Invoke-Command cmdlets.

$PSSessionApplicationName首选项变量是在本地计算机上设置的,但它指定了远程计算机上的侦听器。The $PSSessionApplicationName preference variable is set on the local computer, but it specifies a listener on the remote computer. 如果你指定的应用程序名称在远程计算机上不存在,则用于建立会话的命令将失败。If the application name that you specify doesn't exist on the remote computer, the command to establish the session fails.

$PSSessionConfigurationName$PSSessionConfigurationName

指定用于在当前会话中创建的 pssession 的默认会话配置。Specifies the default session configuration that is used for PSSessions created in the current session.

此首选项变量是在本地计算机上设置的,但它指定了位于远程计算机上的会话配置。This preference variable is set on the local computer, but it specifies a session configuration that's located on the remote computer.

变量的值 $PSSessionConfigurationName 是完全限定的资源 URI。The value of the $PSSessionConfigurationName variable is a fully qualified resource URI.

默认值 http://schemas.microsoft.com/PowerShell/microsoft.PowerShell 表示远程计算机上的 Microsoft PowerShell 会话配置。The default value http://schemas.microsoft.com/PowerShell/microsoft.PowerShell indicates the Microsoft.PowerShell session configuration on the remote computer.

如果只指定配置名称,则会预置以下架构 URI:If you specify only a configuration name, the following schema URI is prepended:

http://schemas.microsoft.com/PowerShell/

你可以使用 ConfigurationName New-PSSessionEnter-PSSession 或 cmdlet 的 ConfigurationName 参数覆盖默认值,并为特定会话选择不同的会话配置 Invoke-CommandYou can override the default and select a different session configuration for a particular session by using the ConfigurationName parameter of the New-PSSession, Enter-PSSession, or Invoke-Command cmdlets.

您可以随时更改此变量的值。You can change the value of this variable at any time. 当你执行此操作时,请记住,你选择的会话配置必须在远程计算机上存在。When you do, remember that the session configuration that you select must exist on the remote computer. 否则,创建使用会话配置的会话的命令将失败。If it doesn't, the command to create a session that uses the session configuration fails.

当远程用户创建连接到此计算机的会话时,此首选项变量不会确定使用的本地会话配置。This preference variable doesn't determine which local session configurations are used when remote users create a session that connects to this computer. 但是,你可以使用本地会话配置的权限来确定哪些用户可以使用它们。However, you can use the permissions for the local session configurations to determine which users may use them.

$PSSessionOption$PSSessionOption

建立远程会话中高级用户选项的默认值。Establishes the default values for advanced user options in a remote session. 这些选项首选项会替代会话选项的系统默认值。These option preferences override the system default values for session options.

$PSSessionOption变量包含 PSSessionOption 对象。The $PSSessionOption variable contains a PSSessionOption object. 有关详细信息,请参阅 PSSessionOptionFor more information, see System.Management.Automation.Remoting.PSSessionOption. 对象的每个属性都表示一个会话选项。Each property of the object represents a session option. 例如, NoCompression 属性将在会话期间启用数据压缩。For example, the NoCompression property turns of data compression during the session.

默认情况下,该 $PSSessionOption 变量包含一个 PSSessionOption 对象,该对象具有所有选项的默认值,如下所示。By default, the $PSSessionOption variable contains a PSSessionOption object with the default values for all options, as shown below.

MaximumConnectionRedirectionCount : 5
NoCompression                     : False
NoMachineProfile                  : False
ProxyAccessType                   : None
ProxyAuthentication               : Negotiate
ProxyCredential                   :
SkipCACheck                       : False
SkipCNCheck                       : False
SkipRevocationCheck               : False
OperationTimeout                  : 00:03:00
NoEncryption                      : False
UseUTF16                          : False
IncludePortInSPN                  : False
OutputBufferingMode               : None
Culture                           :
UICulture                         :
MaximumReceivedDataSizePerCommand :
MaximumReceivedObjectSize         : 209715200
ApplicationArguments              :
OpenTimeout                       : 00:03:00
CancelTimeout                     : 00:01:00
IdleTimeout                       : -00:00:00.0010000

有关这些选项的说明和详细信息,请参阅 PSSessionOptionFor descriptions of these options and more information, see New-PSSessionOption. 有关远程命令和会话的详细信息,请参阅 about_Remoteabout_PSSessionsFor more information about remote commands and sessions, see about_Remote and about_PSSessions.

若要更改首选项变量的值 $PSSessionOption ,请使用 New-PSSessionOption cmdlet 创建一个 PSSessionOption 对象,该对象具有你喜欢的选项值。To change the value of the $PSSessionOption preference variable, use the New-PSSessionOption cmdlet to create a PSSessionOption object with the option values you prefer. 将输出保存在一个名为的变量中 $PSSessionOptionSave the output in a variable called $PSSessionOption.

$PSSessionOption = New-PSSessionOption -NoCompression

若要 $PSSessionOption 在每个 powershell 会话中使用首选项变量,请将 New-PSSessionOption 创建该变量的命令添加 $PSSessionOption 到 powershell 配置文件中。To use the $PSSessionOption preference variable in every PowerShell session, add a New-PSSessionOption command that creates the $PSSessionOption variable to your PowerShell profile. 有关详细信息,请参阅 about_ProfilesFor more information, see about_Profiles.

您可以为特定的远程会话设置自定义选项。You can set custom options for a particular remote session. 您设置的选项优先于系统默认值和 $PSSessionOption 首选项变量的值。The options that you set take precedence over the system defaults and the value of the $PSSessionOption preference variable.

若要设置自定义会话选项,请使用 New-PSSessionOption cmdlet 创建 PSSessionOption 对象。To set custom session options, use the New-PSSessionOption cmdlet to create a PSSessionOption object. 然后,在创建会话的 cmdlet (例如、和)中,使用 PSSessionOption 对象作为 SessionOption 参数的值 New-PSSession Enter-PSSession Invoke-CommandThen, use the PSSessionOption object as the value of the SessionOption parameter in cmdlets that create a session, such as New-PSSession, Enter-PSSession, and Invoke-Command.

$Transcript$Transcript

用于 Start-Transcript 指定脚本文件的名称和位置。Used by Start-Transcript to specify the name and location of the transcript file. 如果未指定 path 参数的值,则将 Start-Transcript 使用全局变量的值中的路径 $TranscriptIf you do not specify a value for the Path parameter, Start-Transcript uses the path in the value of the $Transcript global variable. 如果尚未创建此变量,请将这些 Start-Transcript 脚本 $Home\My Documents 作为文件存储在目录中 \PowerShell_transcript.<time-stamp>.txtIf you have not created this variable, Start-Transcript stores the transcripts in the $Home\My Documents directory as \PowerShell_transcript.<time-stamp>.txt files.

$VerbosePreference$VerbosePreference

确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的详细消息,如 写入-详细 cmdlet 生成的消息。Determines how PowerShell responds to verbose messages generated by a script, cmdlet, or provider, such as the messages generated by the Write-Verbose cmdlet. 详细消息描述执行命令所执行的操作。Verbose messages describe the actions performed to execute a command.

默认情况下,不显示详细消息,但是您可以通过更改的值来更改此行为 $VerbosePreferenceBy default, verbose messages aren't displayed, but you can change this behavior by changing the value of $VerbosePreference.

可以使用 cmdlet 的 verbose 通用参数来显示或隐藏特定命令的详细消息。You can use the Verbose common parameter of a cmdlet to display or hide the verbose messages for a specific command. 有关详细信息,请参阅 about_CommonParametersFor more information, see about_CommonParameters.

有效值如下:The valid values are as follows:

  • 停止 :显示详细消息和错误消息,然后停止执行。Stop : Displays the verbose message and an error message and then stops executing.
  • Inquire :显示详细消息,然后显示一条提示,询问您是否要继续。Inquire : Displays the verbose message and then displays a prompt that asks you whether you want to continue.
  • 继续 :显示详细消息,然后继续执行。Continue : Displays the verbose message and then continues with execution.
  • SilentlyContinue : (默认) 不显示详细消息。SilentlyContinue : (Default) Doesn't display the verbose message. 继续执行。Continues executing.

示例Examples

这些示例显示了不同的值的效果 $VerbosePreference ,并显示了 Verbose 参数重写首选项值。These examples show the effect of the different values of $VerbosePreference and the Verbose parameter to override the preference value.

此示例显示 SilentlyContinue 值(这是默认值)的效果。This example shows the effect of the SilentlyContinue value, that is the default. 此命令使用 message 参数,但不会将消息写入 PowerShell 控制台。The command uses the Message parameter, but doesn't write a message to the PowerShell console.

Write-Verbose -Message "Verbose message test."

使用 详细 参数时,将写入消息。When the Verbose parameter is used, the message is written.

Write-Verbose -Message "Verbose message test." -Verbose
VERBOSE: Verbose message test.

此示例显示了 Continue 值的效果。This example shows the effect of the Continue value. $VerbosePreference变量设置为 Continue ,并显示消息。The $VerbosePreference variable is set to Continue and the message is displayed.

$VerbosePreference = "Continue"
Write-Verbose -Message "Verbose message test."
VERBOSE: Verbose message test.

此示例使用 Verbose 参数,该参数的值为 $false ,它将重写 Continue 值。This example uses the Verbose parameter with a value of $false that overrides the Continue value. 不显示此消息。The message isn't displayed.

Write-Verbose -Message "Verbose message test." -Verbose:$false

此示例显示了 停止 值的影响。This example shows the effect of the Stop value. $VerbosePreference变量设置为 " 停止 ",并显示消息。The $VerbosePreference variable is set to Stop and the message is displayed. 命令已停止。The command is stopped.

$VerbosePreference = "Stop"
Write-Verbose -Message "Verbose message test."
VERBOSE: Verbose message test.
Write-Verbose : The running command stopped because the preference variable
  "VerbosePreference" or common parameter is set to Stop: Verbose message test.
At line:1 char:1
+ Write-Verbose -Message "Verbose message test."

此示例使用 Verbose 参数,该参数的值为 $false ,它将替代 停止 值。This example uses the Verbose parameter with a value of $false that overrides the Stop value. 不显示此消息。The message isn't displayed.

Write-Verbose -Message "Verbose message test." -Verbose:$false

此示例显示了 Inquire 值的效果。This example shows the effect of the Inquire value. $VerbosePreference变量设置为 InquireThe $VerbosePreference variable is set to Inquire . 消息随即显示,并提示用户进行确认。The message is displayed and the user is prompted for confirmation.

$VerbosePreference = "Inquire"
Write-Verbose -Message "Verbose message test."
VERBOSE: Verbose message test.

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [?] Help (default is "Y"):

此示例使用带有 Verbose $false 替代 Inquire 值的值的详细参数。This example uses the Verbose parameter with a value of $false that overrides the Inquire value. 系统不会提示用户并且不显示消息。The user isn't prompted and the message isn't displayed.

Write-Verbose -Message "Verbose message test." -Verbose:$false

$WarningPreference$WarningPreference

确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的警告消息,如 写入警告 cmdlet 生成的消息。Determines how PowerShell responds to warning messages generated by a script, cmdlet, or provider, such as the messages generated by the Write-Warning cmdlet.

默认情况下,会显示警告消息并继续执行,但你可以通过更改的值来更改此行为 $WarningPreferenceBy default, warning messages are displayed and execution continues, but you can change this behavior by changing the value of $WarningPreference.

可以使用 cmdlet 的 WarningAction common 参数确定 PowerShell 如何响应特定命令中的警告。You can use the WarningAction common parameter of a cmdlet to determine how PowerShell responds to warnings from a particular command. 有关详细信息,请参阅 about_CommonParametersFor more information, see about_CommonParameters.

有效值如下:The valid values are as follows:

  • 停止 :显示警告消息和错误消息,然后停止执行。Stop : Displays the warning message and an error message and then stops executing.
  • Inquire :显示警告消息,然后提示继续操作。Inquire : Displays the warning message and then prompts for permission to continue.
  • 继续 : (默认值) 显示警告消息,然后继续执行。Continue : (Default) Displays the warning message and then continues executing.
  • SilentlyContinue :不显示警告消息。SilentlyContinue : Doesn't display the warning message. 继续执行。Continues executing.

示例Examples

这些示例显示了不同的值的效果 $WarningPreferenceThese examples show the effect of the different values of $WarningPreference. WarningAction 参数将覆盖首选项值。The WarningAction parameter overrides the preference value.

此示例显示默认值的效果,然后 继续This example shows the effect of the default value, Continue .

$m = "This action can delete data."
Write-Warning -Message $m
WARNING: This action can delete data.

此示例使用值为 SilentlyContinueWarningAction 参数来禁止显示警告。This example uses the WarningAction parameter with the value SilentlyContinue to suppress the warning. 不显示此消息。The message isn't displayed.

$m = "This action can delete data."
Write-Warning -Message $m -WarningAction SilentlyContinue

此示例将 $WarningPreference 变量更改为 SilentlyContinue 值。This example changes the $WarningPreference variable to the SilentlyContinue value. 不显示此消息。The message isn't displayed.

$WarningPreference = "SilentlyContinue"
$m = "This action can delete data."
Write-Warning -Message $m

此示例在生成警告时使用 WarningAction 参数停止。This example uses the WarningAction parameter to stop when a warning is generated.

$m = "This action can delete data."
Write-Warning -Message $m -WarningAction Stop
WARNING: This action can delete data.
Write-Warning : The running command stopped because the preference variable
  "WarningPreference" or common parameter is set to Stop:
    This action can delete data.
At line:1 char:1
+ Write-Warning -Message $m -WarningAction Stop

此示例将 $WarningPreference 变量更改为 Inquire 值。This example changes the $WarningPreference variable to the Inquire value. 系统将提示用户进行确认。The user is prompted for confirmation.

$WarningPreference = "Inquire"
$m = "This action can delete data."
Write-Warning -Message $m
WARNING: This action can delete data.

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [?] Help (default is "Y"):

此示例使用值为 SilentlyContinueWarningAction 参数。This example uses the WarningAction parameter with the value SilentlyContinue . 命令将继续执行,并且不会显示任何消息。The command continues to execute and no message is displayed.

$m = "This action can delete data."
Write-Warning -Message $m -WarningAction SilentlyContinue

此示例将 $WarningPreference 值更改为 " Stop "。This example changes the $WarningPreference value to Stop .

$WarningPreference = "Stop"
$m = "This action can delete data."
Write-Warning -Message $m
WARNING: This action can delete data.
Write-Warning : The running command stopped because the preference variable
  "WarningPreference" or common parameter is set to Stop:
    This action can delete data.
At line:1 char:1
+ Write-Warning -Message $m

此示例将 WarningActionInquire 值一起使用。This example uses the WarningAction with the Inquire value. 出现警告时,系统将提示用户。The user is prompted when a warning occurs.

$m = "This action can delete data."
Write-Warning -Message $m -WarningAction Inquire
WARNING: This action can delete data.

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [?] Help (default is "Y"):

$WhatIfPreference$WhatIfPreference

确定是否自动为支持它的每个命令启用 WhatIfDetermines whether WhatIf is automatically enabled for every command that supports it. 启用 WhatIf 后,该 cmdlet 会报告命令的预期效果,但不会执行命令。When WhatIf is enabled, the cmdlet reports the expected effect of the command, but doesn't execute the command.

有效值如下:The valid values are as follows:

  • False ( 0 ,未启用) : (默认) WhatIf 不自动启用。False ( 0 , not enabled): (Default) WhatIf isn't automatically enabled. 若要手动启用此参数,请使用 cmdlet 的 WhatIf 参数。To enable it manually, use the cmdlet's WhatIf parameter.
  • True ( 1 ,已启用) :自动对支持该功能的任何命令启用 WhatIfTrue ( 1 , enabled): WhatIf is automatically enabled on any command that supports it. 用户可以使用值为 FalseWhatIf 参数手动禁用它,如 -WhatIf:$falseUsers can use the WhatIf parameter with a value of False to disable it manually, such as -WhatIf:$false.

示例Examples

这些示例显示了不同的值的效果 $WhatIfPreferenceThese examples show the effect of the different values of $WhatIfPreference. 它们演示如何使用 WhatIf 参数覆盖特定命令的首选项值。They show how to use the WhatIf parameter to override the preference value for a specific command.

此示例显示 $WhatIfPreference 变量设置为默认值 False 的影响。This example shows the effect of the $WhatIfPreference variable set to the default value, False . 使用 Get-ChildItem 验证该文件是否存在。Use Get-ChildItem to verify that the file exists. Remove-Item 删除文件。Remove-Item deletes the file. 删除文件后,可以通过验证删除 Get-ChildItemAfter the file is deleted, you can verify the deletion with Get-ChildItem.

Get-ChildItem -Path .\test.txt
Remove-Item -Path ./test.txt
    Directory: C:\Test

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           9/13/2019    10:53             10 test.txt
Get-ChildItem -Path .\test.txt
Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not exist.
At line:1 char:1
+ Get-ChildItem -File test.txt

此示例演示在的值为 False 时使用 WhatIf 参数的效果 $WhatIfPreferenceFalseThis example shows the effect of using the WhatIf parameter when the value of $WhatIfPreference is False .

请确保该文件已存在。Verify that the file exists.

Get-ChildItem -Path .\test2.txt
    Directory: C:\Test

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           2/28/2019    17:06             12 test2.txt

使用 WhatIf 参数确定尝试删除文件的结果。Use the WhatIf parameter to determine the result of attempting to delete the file.

Remove-Item -Path .\test2.txt -WhatIf
What if: Performing the operation "Remove File" on target "C:\Test\test2.txt".

验证文件是否未被删除。Verify that the file wasn't deleted.

Get-ChildItem -Path .\test2.txt
    Directory: C:\Test

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           2/28/2019    17:06             12 test2.txt

此示例显示 $WhatIfPreference 变量设置为值 True 后的效果。This example shows the effect of the $WhatIfPreference variable set to the value, True . 使用 Remove-Item 删除文件时,会显示文件的路径,但不会删除文件。When you use Remove-Item to delete a file, the file's path is displayed, but the file isn't deleted.

尝试删除文件。Attempt to delete a file. 将显示一条消息,其中显示在运行时将会发生什么情况 Remove-Item ,但不会删除该文件。A message is displayed about what would happen if Remove-Item was run, but the file isn't deleted.

$WhatIfPreference = "True"
Remove-Item -Path .\test2.txt
What if: Performing the operation "Remove File" on target "C:\Test\test2.txt".

使用 Get-ChildItem 验证文件是否未被删除。Use Get-ChildItem to verify that the file wasn't deleted.

Get-ChildItem -Path .\test2.txt
    Directory: C:\Test

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           2/28/2019    17:06             12 test2.txt

此示例演示如何在的值为 True 时删除文件 $WhatIfPreferenceTrueThis example shows how to delete a file when the value of $WhatIfPreference is True . 它使用值为的 WhatIf 参数 $falseIt uses the WhatIf parameter with a value of $false. 使用 Get-ChildItem 验证是否已删除该文件。Use Get-ChildItem to verify the file was deleted.

Remove-Item -Path .\test2.txt -WhatIf:$false
Get-ChildItem -Path .\test2.txt
Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path .\test2.txt

下面是不 Get-Process 支持 whatif 并且 Stop-Process 支持 whatif 的 cmdlet 示例。The following are examples of the Get-Process cmdlet that doesn't support WhatIf and Stop-Process that does support WhatIf . $WhatIfPreference变量的值为 TrueThe $WhatIfPreference variable's value is True .

Get-Process 不支持 WhatIfGet-Process doesn't support WhatIf . 执行命令时,它将显示 Winword 进程。When the command is executed, it displays the Winword process.

Get-Process -Name Winword
 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
    130   119.84     173.38       8.39   15024   4 WINWORD

Stop-Process 支持 WhatIfStop-Process does support WhatIf . Winword 进程未停止。The Winword process isn't stopped.

Stop-Process -Name Winword
What if: Performing the operation "Stop-Process" on target "WINWORD (15024)".

您可以 Stop-Process 通过使用值为的 whatif 参数来重写 whatif 行为 $falseYou can override the Stop-Process WhatIf behavior by using the WhatIf parameter with a value of $false. Winword 进程已停止。The Winword process is stopped.

Stop-Process -Name Winword -WhatIf:$false

若要验证 Winword 进程是否已停止,请使用 Get-ProcessTo verify that the Winword process was stopped, use Get-Process.

Get-Process -Name Winword
Get-Process : Cannot find a process with the name "Winword".
  Verify the process name and call the cmdlet again.
At line:1 char:1
+ Get-Process -Name Winword

另请参阅See also

about_Automatic_Variablesabout_Automatic_Variables

about_CommonParametersabout_CommonParameters

about_Environment_Variablesabout_Environment_Variables

about_Profilesabout_Profiles

about_Remoteabout_Remote

about_Scopesabout_Scopes

about_Variablesabout_Variables