about_Preference_Variables

简短说明

自定义 PowerShell 行为的变量。

长说明

PowerShell 包含一组变量,可用于自定义其行为。 这些首选项变量的工作方式类似于基于 GUI 的系统中的选项。

首选项变量会影响 PowerShell 操作环境和环境中运行的所有命令。 某些 cmdlet 具有参数,可用于重写特定命令的首选项行为。

下表列出了首选项变量及其默认值。

变量 默认值
$ConfirmPreference High
$DebugPreference SilentlyContinue
$ErrorActionPreference Continue
$ErrorView ConciseView
$FormatEnumerationLimit 4
$InformationPreference SilentlyContinue
$LogCommandHealthEvent $False(未记录)
$LogCommandLifecycleEvent $False(未记录)
$LogEngineHealthEvent $True(已记录)
$LogEngineLifecycleEvent $True(已记录)
$LogProviderHealthEvent $True(已记录)
$LogProviderLifecycleEvent $True(已记录)
$MaximumHistoryCount 4096
$OFS 空格字符 (" ")
$OutputEncoding (属于UTF8Encoding 对象)的父级。
$ProgressPreference Continue
$PSDefaultParameterValues @{}(空哈希表)
$PSEmailServer $Null(无)
$PSModuleAutoLoadingPreference All
$PSNativeCommandArgumentPassing Windows 上的 Windows,非 Windows 上的 Standard
$PSNativeCommandUseErrorActionPreference $True
$PSSessionApplicationName 'wsman'
$PSSessionConfigurationName 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell'
$PSSessionOption (属于PSSessionOption 对象)的父级。
$PSStyle (属于PSStyle 对象)的父级。
$Transcript $Null(无)
$VerbosePreference SilentlyContinue
$WarningPreference Continue
$WhatIfPreference $False

PowerShell 包含以下用于存储用户首选项的环境变量。 有关这些环境变量的详细信息,请参阅 about_Environment_Variables

  • env:PSExecutionPolicyPreference
  • $env:PSModulePath

注意

如果这些脚本或函数与使用首选项的作用域相同,则对首选项变量的更改仅在脚本和函数中生效。 有关详细信息,请参阅 about_Scopes

使用首选项变量

本文档介绍每个首选项变量。

若要显示特定首选项变量的当前值,请键入变量的名称。 例如,以下命令显示 $ConfirmPreference 变量的值。

 $ConfirmPreference
High

若要更改变量的值,请使用赋值语句。 例如,以下语句将 $ConfirmPreference 参数的值更改为 Medium

$ConfirmPreference = "Medium"

设置的值特定于当前的 PowerShell 会话。 若要使变量在所有 PowerShell 会话中有效,请将它们添加到 PowerShell 配置文件。 有关详细信息,请参阅 about_Profiles

远程工作

在远程计算机上运行命令时,远程命令仅受远程计算机的 PowerShell 客户端中设置的首选项的约束。 例如,运行远程命令时,远程计算机的 $DebugPreference 变量的值决定了 PowerShell 如何响应调试消息。

有关远程命令的详细信息,请参阅 about_Remote

$ConfirmPreference

确定 PowerShell 是否在运行 cmdlet 或函数之前自动提示你进行确认。

$ConfirmPreference 变量采用 ConfirmImpact 枚举值之一:HighMediumLowNone

为 cmdlet 和函数分配 HighMediumLow 的风险。 当 $ConfirmPreference 变量的值小于或等于分配给 cmdlet 或函数的风险时,PowerShell 会在运行 cmdlet 或函数之前自动提示你进行确认。

如果 $ConfirmPreference 变量的值为 None,PowerShell 在运行 cmdlet 或函数之前永远不会自动提示你。

若要更改会话中所有 cmdlet 和函数的确认行为,请更改 $ConfirmPreference 变量的值。

若要重写单个命令的 $ConfirmPreference,请使用 cmdlet 或函数的 Confirm 参数。 若要请求确认,请使用 -Confirm。 若要取消确认,请使用 -Confirm:$false

$ConfirmPreference 的有效值:

  • None:PowerShell 不会自动提示。 若要请求确认特定命令,请使用 cmdlet 或函数的 Confirm 参数。
  • Low:在运行低、中或高风险的 cmdlet 或函数之前,PowerShell 会提示确认。
  • Medium:在运行中或高风险的 cmdlet 或函数之前,PowerShell 会提示确认。
  • High:在运行高风险的 cmdlet 或函数之前,PowerShell 会提示确认。

详细说明

PowerShell 可以在执行操作之前自动提示你进行确认。 例如,当 cmdlet 或函数显著影响系统删除数据或使用大量系统资源时。

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"):

风险的估计是 cmdlet 或函数的属性,称为其 ConfirmImpact。 用户无法更改它。

可能给系统带来风险的 cmdlet 和函数具有 Confirm 参数,可用于请求或取消单个命令的确认。

由于大多数 cmdlet 和函数都使用 Medium 的默认风险值,ConfirmImpact$ConfirmPreference 的默认值为 High,因此自动确认很少发生。 但是,可以通过将 $ConfirmPreference 的值更改为 MediumLow 来激活自动确认。

示例

此示例显示 $ConfirmPreference 变量的默认值 High 的效果。 High 值仅确认高风险 cmdlet 和函数。 由于大多数 cmdlet 和函数存在中风险,因此不会自动确认它们,并且 Remove-Item 会删除该文件。 将 -Confirm 添加到命令提示符,提示用户进行确认。

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

使用 -Confirm 请求确认。

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 值更改为 Medium 的效果。 由于大多数 cmdlet 和函数都是中风险,因此会自动确认它们。 若要取消单个命令的确认提示,请使用 Confirm 参数的值 $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

确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的调试消息,或命令行中的 Write-Debug 命令。

$DebugPreference 变量采用 ActionPreference 枚举值之一:SilentlyContinueStopContinueInquireIgnoreSuspendBreak

某些 cmdlet 显示调试消息,这些消息通常是专为程序员和技术支持专业人员设计的技术消息。 默认情况下,不会显示调试消息,但可以通过更改 $DebugPreference 的值来显示调试消息。

可以使用 cmdlet 的 Debug 通用参数来显示或隐藏特定命令的调试消息。 有关详细信息,请参阅 about_CommonParameters

有效值如下:

  • Break - 在发生错误或引发异常时进入调试器。
  • Stop:显示调试消息并停止执行。 将错误写入控制台。
  • Inquire:显示调试消息并询问是否继续。
  • Continue:显示调试消息并继续执行。
  • SilentlyContinue:(默认值)无效果。 不会显示调试消息,并且在不会中断的情况下继续执行。

Debug 通用参数添加到命令,当命令配置为生成调试消息时,将 $DebugPreference 变量的值更改为 Continue

示例

以下示例演示在命令行中输入 Write-Debug 命令时更改 $DebugPreference 值的效果。 此更改会影响所有调试消息,包括 cmdlet 和脚本生成的消息。 这些示例显示了 Debug 参数,该参数显示或隐藏与单个命令相关的调试消息。

此示例显示 $DebugPreference 变量的默认值 SilentlyContinue 的效果。 默认情况下,不会显示 Write-Debug cmdlet 的调试消息,并且继续处理。 使用 Debug 参数时,它将重写单个命令的首选项。 不显示调试消息。

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

此示例显示了使用 Continue 值的 $DebugPreference 的效果。 显示调试消息,命令继续处理。

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

此示例使用 Debug 参数和 $false 值来禁止显示单个命令的消息。 不显示调试消息。

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

此示例显示 $DebugPreference 设置为 Stop 值的效果。 显示调试消息并停止命令。

$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 值来禁止显示单个命令的消息。 不显示调试消息,并且不停止处理。

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

此示例显示 $DebugPreference 设置为 Inquire 值的效果。 显示调试消息,并提示用户进行确认。

$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 值来禁止显示单个命令的消息。 不显示调试消息,并且继续处理。

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

$ErrorActionPreference

确定 PowerShell 如何响应非终止错误,即不会停止 cmdlet 处理的错误。 例如,在命令行或脚本、cmdlet 或提供程序中,例如 Write-Error cmdlet 生成的错误。

$ErrorActionPreference 变量采用 ActionPreference 枚举值之一:SilentlyContinueStopContinueInquireIgnoreSuspendBreak

可以使用 cmdlet 的 ErrorAction 通用参数来重写特定命令的首选项。

有效值如下:

  • Break - 在发生错误或引发异常时进入调试器。
  • Continue:(默认值)显示错误消息并继续执行。
  • Ignore:禁止显示错误消息并继续执行命令。 Ignore 值适用于按命令使用,而不是用作保存的首选项。 Ignore 不是 $ErrorActionPreference 变量的有效值。
  • Inquire:显示错误消息并询问是否继续。
  • SilentlyContinue:无效果。 不显示错误消息,并且在不会中断的情况下继续执行。
  • Stop:显示错误消息并停止执行。 除了生成的错误之外,Stop 值还会向错误流生成 ActionPreferenceStopException 对象。
  • Suspend:自动挂起工作流作业以允许进一步调查。 调查后,可以恢复工作流。 Suspend 值适用于按命令使用,而不是用作保存的首选项。 Suspend 不是 $ErrorActionPreference 变量的有效值。

$ErrorActionPreferenceErrorAction 参数不会影响 PowerShell 响应停止 cmdlet 处理的终止错误的方式。 有关 ErrorAction 通用参数的详细信息,请参阅 about_CommonParameters

许多本机命令都会写入到 stderr,来将其作为获取额外信息的备用流。 查找错误时,此行为可能会导致混淆,如果将 $ErrorActionPreference 设置为静音输出的状态,则用户可能会丢失额外的输出信息。

从 PowerShell 7.2 开始,从本机命令重定向的错误记录(如使用重定向运算符 (2>&1))时不会写入 $Error 变量,首选项变量 $ErrorActionPreference 不会影响重定向的输出。

PowerShell 7.3 添加了一项实验性功能,可用于控制写入 stderr 的消息的处理方式。

有关详细信息,请参阅 $PSNativeCommandUseErrorActionPreference

示例

这些示例显示了 $ErrorActionPreference 变量的不同值的效果。 ErrorAction 参数用于重写 $ErrorActionPreference 值。

此示例显示$ErrorActionPreference默认值 Continue。 生成非终止错误。 显示消息,并且继续处理。

# 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默认值 Inquire。 生成错误并显示操作提示。

# 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 设置为 SilentlyContinue。 已禁止显示错误消息。

# 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 设置为 Stop。 它还显示为 $Error 变量生成的额外对象。

# Change the ErrorActionPreference to 'Stop'
$ErrorActionPreference = 'Stop'
# Error message 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

确定 PowerShell 中错误消息的显示格式。

$ErrorView 变量采用 ErrorView 枚举值之一:NormalViewCategoryViewConciseView

有效值如下:

  • ConciseView:(默认值)为高级模块生成器提供简洁的错误消息和重构视图。 从 PowerShell 7.2 起,如果错误来自命令行或脚本模块,则输出是单行错误消息。 否则,会收到包含错误的多行错误消息,以及指向该行中发生错误的指针。 如果终端支持虚拟终端,则 ANSI 颜色代码用于提供颜色主题。 可以在 $Host.PrivateData.ErrorAccentColor 更改主题色。 使用 Get-Error cmdlet 全面详细查看完全限定的错误,包括内部异常。

    PowerShell 7 中添加了 ConciseView

  • NormalView:为大多数用户设计的详细视图。 由错误的说明和错误中涉及的对象的名称组成。

  • CategoryView:为生产环境设计的简洁结构化视图。 格式如下所示:

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

有关 CategoryView 中的字段的详细信息,请参阅 ErrorCategoryInfo 类。

示例

此示例显示当 $ErrorView 值为默认值 ConciseView 时,如何显示错误。 Get-ChildItem 用于查找不存在的文件。

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

此示例显示当 $ErrorView 值为默认值 ConciseView 时,如何显示错误。 运行 Script.ps1 并从 Get-Item 语句引发错误。

./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 时,如何显示错误。 Get-ChildItem 用于查找不存在的文件。

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 时,会出现相同的错误。

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

此示例演示 $ErrorView 的值仅影响错误显示。 它不会更改存储在 $Error 自动变量中的错误对象的结构。 有关 $Error 自动变量的信息,请参阅 about_automatic_variables

以下命令采用与错误数组中最新错误关联的 ErrorRecord 对象、元素 0,并设置列表中对象的属性的格式。

$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 的值小于枚举项数时,PowerShell 会添加省略号 (...),以指示未显示的项。

有效值:整数 (Int32)

默认值:4

示例

此示例演示如何使用 $FormatEnumerationLimit 变量来改进枚举项的显示。

此示例中的命令生成一个表,其中列出了两个组中计算机上运行的所有服务:一个用于运行服务,另一个用于停止服务。 它使用 Get-Service 命令获取所有服务,然后通过管道将结果发送到 Group-Object cmdlet,该 cmdlet 按服务状态对结果进行分组。

结果是一个表,其中列出了名称列中的状态,以及列中的进程。 若要更改列标签,请使用哈希表,请参阅 about_Hash_Tables。 有关详细信息,请参阅 Format-Table 中的示例。

查找 $FormatEnumerationLimit 的当前值。

$FormatEnumerationLimit
4

列出按状态分组的所有服务。 每个状态的列中最多列出四项服务,因为 $FormatEnumerationLimit 的值为 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...}

若要增加列出的项数,将 $FormatEnumerationLimit 的值增加到 1000。 使用 Get-ServiceGroup-Object 来显示服务。

$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 参数一起使用,以显示服务列表。

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 变量可以设置要向用户显示的信息流首选项。 具体而言,通过添加 Write-Information cmdlet 添加到命令或脚本的信息性消息。 如果使用 InformationAction 参数,则其值将重写 $InformationPreference 变量的值。 PowerShell 5.0 中引入了 Write-Information

$InformationPreference 变量采用 ActionPreference 枚举值之一:SilentlyContinueStopContinueInquireIgnoreSuspendBreak

有效值如下:

  • 中断 - 写入信息流时输入调试器。
  • Stop:在 Write-Information 命令出现时停止命令或脚本。
  • Inquire:显示在 Write-Information 命令中指定的信息性消息,然后询问是否继续。
  • Continue:显示信息性消息,并继续运行。
  • SilentlyContinue:(默认值)无效果。 不会显示信息性消息,并且脚本将继续不中断。

$Log*Event

Log*Event 首选项变量决定在事件查看器中写入 PowerShell 事件日志的类型。 默认情况下,仅记录引擎和提供程序事件。 但是,可以使用 Log*Event 首选项变量来自定义日志,例如记录有关命令的事件。

Log*Event 首选项变量如下所示:

  • $LogCommandHealthEvent:记录命令初始化和处理中的错误和异常。 默认值为 $false(未记录)。
  • $LogCommandLifecycleEvent:在命令发现中记录命令和命令管道的启动和停止以及安全异常。 默认值为 $false(未记录)。
  • $LogEngineHealthEvent:记录会话的错误和失败。 默认值为 $true(已记录)。
  • $LogEngineLifecycleEvent:记录会话的打开和关闭。 默认值为 $true(已记录)。
  • $LogProviderHealthEvent:记录提供程序错误,例如读取和写入错误、查找错误和调用错误。 默认值为 $true(已记录)。
  • $LogProviderLifecycleEvent:记录添加和删除 PowerShell 提供程序的操作。 默认值为 $true(已记录)。 有关 PowerShell 提供程序的信息,请参阅 about_Providers

若要启用 Log*Event,请键入值为 $true 的变量,例如:

$LogCommandLifeCycleEvent = $true

若要禁用事件类型,请键入值为 $false 的变量,例如:

$LogCommandLifeCycleEvent = $false

启用的事件仅适用于当前 PowerShell 控制台。 若要将配置应用于所有控制台,请在 PowerShell 配置文件中保存变量设置。 有关详细信息,请参阅 about_Profiles

$MaximumHistoryCount

确定当前会话的命令历史记录中保存的命令数。

有效值:1 - 32768 (Int32)

默认:4096

若要确定当前保存在命令历史记录中的命令数,请键入:

(Get-History).Count

若要查看会话历史记录中保存的命令,请使用 Get-History cmdlet。 有关详细信息,请参阅 about_History

$OFS

输出字段分隔符 (OFS) 指定分隔转换为字符串的数组元素的字符。

有效值:任何字符串。

默认值:空格

默认情况下,$OFS 变量不存在,输出文件分隔符是一个空格,但可以添加此变量并将其设置为任何字符串。 可以通过键入 $OFS="<value>" 来更改会话中 $OFS 的值。

注意

如果希望脚本、模块或配置输出中的空格 (" ") 的默认值,请注意代码中的其他位置尚未更改 $OFS 默认值。

示例

此示例显示当数组转换为字符串时,将使用空格分隔值。 在这种情况下,整数数组存储在变量中,然后变量被强制转换为字符串。

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

若要更改分隔符,请通过向其分配值来添加 $OFS 变量。 变量必须命名为 $OFS

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

若要还原默认行为,可以将空格 (" ") 分配给 $OFS 的值或删除变量。 以下命令将删除该变量,然后验证分隔符是否为空格。

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

$OutputEncoding

确定 PowerShell 将数据注入本机应用程序时使用的字符编码方法。

注意

在大多数情况下,其 $OutputEncoding 值应与值 [Console]::InputEncoding保持一致。

有效值如下所示:从编码类派生的对象,例如 ASCIIEncodingUTF7EncodingUTF8EncodingUTF32EncodingUnicodeEncoding

默认值UTF8Encoding 对象。

示例

第一个命令查找 $OutputEncoding 的值。 由于该值是一个编码对象,因此只显示其 EncodingName 属性。

$OutputEncoding.EncodingName

其余示例使用以下保存的 hexdump.ps1 PowerShell 脚本来说明其 $OutputEncoding行为。

$inputStream = [Console]::OpenStandardInput()
try {
    $buffer = [byte[]]::new(1024)
    $read = $inputStream.Read($buffer, 0, $buffer.Length)
    Format-Hex -InputObject $buffer -Count $read
} finally {
    $inputStream.Dispose()
}

以下示例演示在通过管道传递到上面创建的字符串值 café 时如何编码为 hexdump.ps1 字节。 它演示如何使用 UTF8Encoding 方案对字符串值进行编码。

'café' | pwsh -File ./hexdump.ps1
   Label: Byte[] (System.Byte[]) <28873E25>

          Offset Bytes                                           Ascii
                 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
          ------ ----------------------------------------------- -----
0000000000000000 63 61 66 C3 A9 0D 0A                            caf�

以下示例演示如何在将编码更改为 UnicodeEncoding 时更改字节数。

$OutputEncoding = [System.Text.Encoding]::Unicode
'café' | pwsh -File ./hexdump.ps1
   Label: Byte[] (System.Byte[]) <515A7DC3>

          Offset Bytes                                           Ascii
                 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
          ------ ----------------------------------------------- -----
0000000000000000 FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00       ÿþc a f é � �

$ProgressPreference

确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的进度更新,例如由 Write-Progress cmdlet 生成的进度栏。 Write-Progress cmdlet 创建显示命令状态的进度栏。

$ProgressPreference 变量采用 ActionPreference 枚举值之一:SilentlyContinueStopContinueInquireIgnoreSuspendBreak

有效值如下:

  • 中断 - 写入进度流时输入调试器。
  • Stop:不显示进度栏。 而是显示错误消息并停止执行。
  • Inquire:不显示进度栏。 提示继续权限。 如果使用 YA 进行答复,则会显示进度栏。
  • Continue:(默认值)显示进度栏并继续执行。
  • SilentlyContinue:执行命令,但不显示进度栏。

$PSDefaultParameterValues

指定 cmdlet 和高级函数的参数的默认值。 $PSDefaultParameterValues 的值是一个哈希表,其关键值由冒号 (:) 分隔的 cmdlet 名称和参数名称组成。 该值是指定的自定义默认值。

PowerShell 3.0 中引入了 $PSDefaultParameterValues

有关此首选项变量的详细信息,请参阅 about_Parameters_Default_Values

$PSEmailServer

指定用于发送电子邮件的默认电子邮件服务器。 此首选项变量由发送电子邮件的 cmdlet 使用,例如 Send-MailMessage cmdlet。

$PSModuleAutoloadingPreference

启用和禁用会话中模块的自动导入。 默认情况下,变量 $PSModuleAutoloadingPreference 不存在。 未定义变量时的默认行为与 $PSModuleAutoloadingPreference = 'All' 相同。

若要自动导入模块,请获取或使用模块中包含的命令。

$PSModuleAutoloadingPreference 变量采用枚举 PSModuleAutoLoadingPreference 值之一:

  • All:首次使用时会自动导入模块。
  • ModuleQualified:仅当用户在模块中使用命令的模块限定名称时,模块才会自动导入。 例如,如果用户键入 MyModule\MyCommand,PowerShell 将导入 MyModule 模块。
  • None:禁用模块的自动导入。 若要导入模块,请使用 Import-Module cmdlet。

有关模块自动导入的详细信息,请参阅 about_Modules

$PSNativeCommandArgumentPassing

PowerShell 7.3 更改了对本机命令的命令行进行分析的方式。 新的 $PSNativeCommandArgumentPassing 首选项变量控制此行为。

注意

新行为是对以前行为的中断性变更。 在调用本机应用程序时,这可能会中断用于解决各种问题的脚本和自动化。

使用自动变量 $PSNativeCommandArgumentPassing 可以在运行时选择行为。 有效值是 LegacyStandardWindowsLegacy 是历史行为。

系统在默认情况下会将 $PSNativeCommandArgumentPassing 变量定义为特定于平台的值。

  • 在 Windows 上,首选项设置为 Windows
  • 在非 Windows 平台上,首选项设置为 Standard
  • 如果删除了 $PSNativeCommandArgumentPassing 变量,PowerShell 将采用 Standard 行为。

WindowsStandard 模式的行为是相同的,但在 Windows 模式下,PowerShell 使用运行以下文件时传递的参数 Legacy 行为。

  • cmd.exe
  • cscript.exe
  • find.exe
  • sqlcmd.exe
  • wscript.exe
  • 以该内容结尾的文件:
    • .bat
    • .cmd
    • .js
    • .vbs
    • .wsf

如果 $PSNativeCommandArgumentPassing 设置为 LegacyStandard,分析程序不会检查这些文件。 有关新行为的示例,请参阅 about_Parsing

PowerShell 7.3 还添加了跟踪本机命令的参数绑定的功能。 有关更多信息,请参阅 Trace-Command

$PSNativeCommandUseErrorActionPreference

此首选项变量在 PowerShell 7.3 及更高版本中提供,启用了 PSNativeCommandErrorActionPreference 功能。

启用此功能后,当 $PSNativeCommandUseErrorActionPreference$true 时,具有非零退出代码的本机命令会根据 $ErrorActionPreference 发出错误。

注意

PSNativeCommandUseErrorActionPreference 是 PowerShell 7.3 中添加的试验性功能。 有关详细信息,请参阅使用试验性功能

某些本机命令(如 robocopy)使用非零退出代码来表示错误以外的信息。 在这些情况下,可以暂时禁用该行为,并防止非零退出代码发出错误。

& {
    # Disable $PSNativeCommandUseErrorActionPreference for this scriptblock
    $PSNativeCommandUseErrorActionPreference = $false
    robocopy.exe D:\reports\operational "\\reporting\ops" CY2022Q4.md
    if ($LASTEXITCODE -gt 8) {
        throw "robocopy failed with exit code $LASTEXITCODE"
    }
}

在此示例中,变量 $PSNativeCommandUseErrorActionPreference 在脚本块内更改。 更改是脚本块的本地更改。 当 scriptblock 退出时,变量还原其以前的值。

$PSSessionApplicationName

指定使用 Web Services for Management (WS-Management) 技术的远程命令的默认应用程序名称。 有关详细信息,请参阅关于 Windows 远程管理

系统默认应用程序名称为 WSMAN,但可以使用此首选项变量更改默认值。

应用程序名称是连接 URI 中的最后一个节点。 例如,以下示例 URI 中的应用程序名称为 WSMAN

http://Server01:8080/WSMAN

远程命令未指定连接 URI 或应用程序名称时,将使用默认应用程序名称。

WinRM 服务使用应用程序名称来选择为连接请求提供服务的侦听器。 参数的值应与远程计算机上的侦听器的 URLPrefix 属性值相匹配。

若要重写系统默认值和此变量的值,并为特定会话选择其他应用程序名称,请使用 New-PSSessionEnter-PSSessionInvoke-Command cmdlet 的 ConnectionURIApplicationName 参数。

$PSSessionApplicationName 首选项变量在本地计算机上设置,但它指定远程计算机上的侦听器。 如果远程计算机上不存在指定的应用程序名称,则建立会话的命令将失败。

$PSSessionConfigurationName

指定用于在当前会话中创建新会话的默认会话配置。

此首选项变量在本地计算机上设置,但它指定位于远程计算机上的会话配置。

$PSSessionConfigurationName 变量的值是完全限定的资源 URI。

默认值 http://schemas.microsoft.com/PowerShell/microsoft.PowerShell 指示远程计算机上的 Microsoft.PowerShell 会话配置。

如果仅指定配置名称,则前面有以下架构 URI:

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

可以使用 New-PSSessionEnter-PSSessionInvoke-Command cmdlet 的 ConfigurationName 参数重写默认值并选择特定会话的不同会话配置。

可以随时更改此变量的值。 执行此操作时,请记住,所选的会话配置必须存在于远程计算机上。 如果没有,创建使用会话配置的会话的命令将失败。

当远程用户创建连接到此计算机的会话时,此首选项变量不会决定使用哪个本地会话配置。 但可以为本地会话配置设置权限,决定哪些用户可以使用配置。

$PSSessionOption

为远程会话中的高级用户选项建立默认值。 这些选项首选项将覆盖会话选项的系统默认值。

$PSSessionOption 变量包含 PSSessionOption 对象。 有关详细信息,请参阅 System.Management.Automation.Remoting.PSSessionOption。 对象的每个属性都表示一个会话选项。 例如,NoCompression 关闭会话期间的数据压缩。

默认情况下,$PSSessionOption 变量包含 PSSessionOption 对象,其中包含所有选项的默认值,如下所示。

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

有关这些选项和详细信息的说明,请参阅 New-PSSessionOption。 有关远程命令和会话的详细信息,请参阅 about_Remoteabout_PSSessions

若要更改 $PSSessionOption 首选项变量值,请使用 New-PSSessionOption cmdlet 创建 PSSessionOption,选项值自定义。 在 $PSSessionOption 变量中保存输出。

$PSSessionOption = New-PSSessionOption -NoCompression

若要在每个 PowerShell 会话中使用 $PSSessionOption 首选项变量,请将创建 $PSSessionOption 变量的 New-PSSessionOption 命令添加到 PowerShell 配置文件。 有关详细信息,请参阅 about_Profiles

可以为特定的远程会话设置自定义选项。 设置的选项优先于系统默认值和 $PSSessionOption 首选项变量的值。

若要设置自定义会话选项,请使用 New-PSSessionOption cmdlet 创建 PSSessionOption 对象。 然后,在创建会话的 cmdlet 中使用 PSSessionOption 对象作为 SessionOption 参数的值,例如 New-PSSessionEnter-PSSessionInvoke-Command

$PSStyle

从 PowerShell 7.2 开始,可以访问 $PSStyle 自动变量以查看和更改 ANSI 字符串输出的呈现。 $PSStylePSStyle 类的实例。 此类的成员定义包含 ANSI 转义序列的字符串,这些序列控制终端中文本的呈现。

基成员会返回映射到其名称的 ANSI 转义序列的字符串。 值可设置为允许自定义。 属性名称使你能够更轻松地使用 Tab 补全创建修饰字符串。 例如:

"$($PSStyle.Background.BrightCyan)Power$($PSStyle.Underline)$($PSStyle.Bold)Shell$($PSStyle.Reset)"

背景前景成员还具有能指定 24 位颜色的 FromRgb() 方法。

有关 $PSStyle 的详细信息,请参阅 about_ANSI_Terminals

$Transcript

Start-Transcript 用来指定脚本文件的名称和位置。 如果没有为 Path 参数指定值,Start-Transcript 将使用 $Transcript 全局变量值中的路径。 如果尚未创建此变量, Start-Transcript 请使用默认名称将脚本存储在以下位置:

  • 在 Windows 上:$HOME\Documents
  • 在 Linux 或 macOS 上: $HOME

默认文件名为: PowerShell_transcript.<computername>.<random>.<timestamp>.txt

$VerbosePreference

决定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的详细消息,例如由 Write-Verbose cmdlet 生成的消息。 详细消息描述执行命令的操作。

默认情况下,不显示详细消息,但可以通过更改 $VerbosePreference 的值来更改此行为。

$VerbosePreference 变量采用 ActionPreference 枚举值之一:SilentlyContinueStopContinueInquireIgnoreSuspendBreak

有效值如下:

  • 中断 - 写入详细流时输入调试器。
  • Stop:显示详细消息和错误消息,然后停止执行。
  • Inquire:显示详细消息,然后显示提示询问是否继续。
  • Continue:显示详细消息并继续执行。
  • SilentlyContinue:(默认值)不显示详细消息。 继续执行。

可以使用 cmdlet 的 Verbose 通用参数来显示或隐藏特定命令的详细消息。 有关详细信息,请参阅 about_CommonParameters

示例

这些示例显示了 $VerbosePreference 的不同值和 Verbose 参数的效果,以重写首选项值。

此示例显示了 SilentlyContinue (即默认值)值的效果。 该命令使用 Message 参数,但不会将消息写入 PowerShell 控制台。

Write-Verbose -Message "Verbose message test."

使用 Verbose 参数时,将写入消息。

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

此示例显示 Continue 值的效果。 $VerbosePreference 变量设置为 Continue,因此显示消息。

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

此示例使用 Verbose 参数,该参数的值为 $false,重写 Continue 值。 不显示消息。

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

此示例显示 Stop 值的效果。 $VerbosePreference 变量设置为 Stop,因此显示消息。 命令停止。

$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,重写 Stop 值。 不显示消息。

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

此示例显示 Inquire 值的效果。 $VerbosePreference 变量设置为 Inquire。 显示消息,并提示用户进行确认。

$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 值。 不会提示用户,并且不会显示消息。

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

$WarningPreference

决定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的警告消息,例如由 Write-Warning cmdlet 生成的消息。

默认情况下,将显示警告消息并继续执行,但可以通过更改 $WarningPreference 的值来更改此行为。

$WarningPreference 变量采用 ActionPreference 枚举值之一:SilentlyContinueStopContinueInquireIgnoreSuspendBreak

有效值如下:

  • 中断 - 在写入警告消息时输入调试器。
  • Stop:显示警告消息和错误消息,然后停止执行。
  • Inquire:显示警告消息,然后提示要求权限以继续。
  • Continue:(默认值)显示警告消息,然后继续执行。
  • SilentlyContinue:不显示警告消息。 继续执行。

可以使用 cmdlet 的 WarningAction 通用参数来决定 PowerShell 如何响应来自特定命令的警告。 有关详细信息,请参阅 about_CommonParameters

示例

这些示例显示了 $WarningPreference 各值的效果。 WarningAction 参数重写首选项值。

此示例显示默认值 Continue 的效果。

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

此示例使用 WarningAction 参数的 SilentlyContinue 值来禁止显示警告。 不显示消息。

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

此示例将 $WarningPreference 变量更改为 SilentlyContinue 值。 不显示消息。

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

此示例使用 WarningAction 参数在生成警告时停止。

$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。 系统会提示用户进行确认。

$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"):

此示例使用 WarningAction 参数的 SilentlyContinue值。 命令继续执行,不显示任何消息。

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

本示例将 $WarningPreference 值更改为 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 值。 出现警告时,系统会提示用户。

$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

决定是否为每个支持的命令自动启用 WhatIf。 启用 WhatIf 后,cmdlet 将报告命令的预期效果,但不执行命令。

有效值如下:

  • False0,不启用):(默认)不自动启用 WhatIf。 若要手动启用,请使用 cmdlet 的 WhatIf 参数。
  • True1,启用):在支持 WhatIf 命令上自动启用。 用户可以将 WhatIf 参数值设置为 False 以手动禁用,例如 -WhatIf:$false

示例

这些示例显示了 $WhatIfPreference 各值的效果。 它们演示如何使用 WhatIf 参数重写特定命令的首选项值。

此示例显示 $WhatIfPreference 变量设置为默认值 (False) 的效果。 使用 Get-ChildItem 确认文件存在。 Remove-Item 删除文件。 删除文件后,可以使用 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

本示例显示当 $WhatIfPreference 值为 False 时,使用 WhatIf 参数的效果。

请确保该文件已存在。

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

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

使用 WhatIf 参数来决定尝试删除文件的结果。

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

确认文件未删除。

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

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

此示例显示将 $WhatIfPreference 变量值设置为 True 的效果。 使用 Remove-Item 删除文件时,将显示文件的路径,但不会删除文件。

尝试删除文件。 将显示一条消息,说明运行 Remove-Item 时会发生什么情况,但不会删除文件。

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

使用 Get-ChildItem 确认文件未删除。

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

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

此示例演示如何在 $WhatIfPreference 的值为 True 时删除文件。 使用 WhatIf 参数的 $false 值。 使用 Get-ChildItem 确认文件已删除。

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

以下示例分别显示不支持 WhatIfGet-Process ccmdlet,和支持 WhatIfStop-Process$WhatIfPreference 变量值为 True

Get-Process 不支持 WhatIf。 执行命令时,将显示 Winword 进程。

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 支持 WhatIfWinword 进程不停止。

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

可以使用 WhatIf 参数(值为 $false)重写 Stop-ProcessWhatIf 行为。 Winword 进程停止。

Stop-Process -Name Winword -WhatIf:$false

若要确认 Winword 进程已停止,请使用 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

另请参阅