关于首选项变量
简短说明
自定义 PowerShell 行为的变量。
长说明
PowerShell 包含一组变量,可用于自定义其行为。 这些首选项变量的工作方式类似于基于 GUI 的系统中的选项。
首选项变量会影响 PowerShell 操作环境和所有命令在环境中运行。 在许多情况下,cmdlet 具有可用于替代特定命令的首选项行为的参数。
下表列出了首选项变量及其默认值。
变量 | 默认值 |
---|---|
$ConfirmPreference |
高 |
$DebugPreference |
SilentlyContinue |
$ErrorActionPreference |
继续 |
$ErrorView |
NormalView |
$FormatEnumerationLimit |
4 |
$InformationPreference |
SilentlyContinue |
$LogCommandHealthEvent |
未记录) 的 false ( |
$LogCommandLifecycleEvent |
未记录) 的 false ( |
$LogEngineHealthEvent |
记录) (真实 |
$LogEngineLifecycleEvent |
记录) (真实 |
$LogProviderLifecycleEvent |
记录) (真实 |
$LogProviderHealthEvent |
记录) (真实 |
$MaximumAliasCount |
4096 |
$MaximumDriveCount |
4096 |
$MaximumErrorCount |
256 |
$MaximumFunctionCount |
4096 |
$MaximumHistoryCount |
4096 |
$MaximumVariableCount |
4096 |
$OFS |
(空格字符 (" " ) ) |
$OutputEncoding |
ASCIIEncoding 对象 |
$ProgressPreference |
继续 |
$PSDefaultParameterValues |
(None - 空哈希表) |
$PSEmailServer |
(无) |
$PSModuleAutoLoadingPreference |
全部 |
$PSSessionApplicationName |
WSMAN |
$PSSessionConfigurationName |
https://schemas.microsoft.com/PowerShell/microsoft.PowerShell |
$PSSessionOption |
请参阅 $PSSessionOption |
$VerbosePreference |
SilentlyContinue |
$WarningPreference |
继续 |
$WhatIfPreference |
0 |
PowerShell 包含以下用于存储用户首选项的环境变量。 有关这些环境变量的详细信息,请参阅 about_Environment_Variables。
env:PSExecutionPolicyPreference
$env:PSModulePath
使用首选项变量
本文档介绍每个首选项变量。
若要显示特定首选项变量的当前值,请键入变量的名称。 例如,以下命令显示 $ConfirmPreference
变量的值。
$ConfirmPreference
High
若要更改变量的值,请使用赋值语句。 例如,以下语句将 $ConfirmPreference
参数的值更改为 Medium。
$ConfirmPreference = "Medium"
设置的值特定于当前 PowerShell 会话。 若要使变量在所有 PowerShell 会话中有效,请将其添加到 PowerShell 配置文件。 有关详细信息,请参阅 about_Profiles。
远程工作
在远程计算机上运行命令时,远程命令仅受远程计算机 PowerShell 客户端中设置的首选项的约束。 例如,运行远程命令时,远程计算机的 $DebugPreference
变量的值将确定 PowerShell 如何响应调试消息。
有关远程命令的详细信息,请参阅 about_Remote。
$ConfirmPreference
确定 PowerShell 在运行 cmdlet 或函数之前是否自动提示你进行确认。
变量 $ConfirmPreference
的有效值为 高、 中或 低。 Cmdlet 和函数的风险为 高、 中或 低。 当变量的值 $ConfirmPreference
小于或等于分配给 cmdlet 或函数的风险时,PowerShell 会在运行 cmdlet 或函数之前自动提示你进行确认。
如果变量的 $ConfirmPreference
值为 None,则 PowerShell 在运行 cmdlet 或函数之前永远不会自动提示你。
若要更改会话中所有 cmdlet 和函数的确认行为,请更改 $ConfirmPreference
变量的值。
若要替代 $ConfirmPreference
单个命令的 ,请使用 cmdlet 或函数的 Confirm 参数。 若要请求确认,请使用 -Confirm
。 若要禁止确认,请使用 -Confirm:$false
。
的有效值 $ConfirmPreference
:
- 无:PowerShell 不会自动提示。 若要请求特定命令的确认,请使用 cmdlet 或函数的 Confirm 参数。
- 低:在运行低、中或高风险的 cmdlet 或函数之前,PowerShell 会提示进行确认。
- 中等:PowerShell 在运行具有中等或高风险的 cmdlet 或函数之前,会提示进行确认。
- 高:在运行具有高风险的 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 [S] Suspend
[?] Help (default is "Y"):
风险估算是 cmdlet 或称为 ConfirmImpact 的函数的属性。 用户无法更改它。
可能会给系统带来风险的 Cmdlet 和函数具有 一个 Confirm 参数,可用于请求或禁止对单个命令进行确认。
由于大多数 cmdlet 和函数使用中的默认风险值 ConfirmImpact,默认值$ConfirmPreference
为“高”,因此很少发生自动确认。 但是,可以通过将 的值 $ConfirmPreference
更改为 “中” 或“ 低”来激活自动确认。
示例
此示例演示变量默认值 High 的效果$ConfirmPreference
。 高值仅确认高风险 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 [S] Suspend
[?] Help (default is "Y"):
以下示例演示将 的值 $ConfirmPreference
更改为 Medium 的效果。 由于大多数 cmdlet 和函数风险中等,因此会自动确认。 若要取消单个命令的确认提示,请使用值为 的 $false
Confirm 参数。
$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 [S] Suspend
[?] Help (default is "Y"):
Remove-Item -Path C:\temp3.txt -Confirm:$false
$DebugPreference
确定 PowerShell 如何响应脚本、cmdlet 或提供程序 Write-Debug
或命令行中的命令生成的调试消息。
某些 cmdlet 显示调试消息,这些消息通常是专为程序员和技术支持专业人员设计的技术消息。 默认情况下,不会显示调试消息,但可以通过更改 的值 $DebugPreference
来显示调试消息。
可以使用 cmdlet 的 Debug 通用参数来显示或隐藏特定命令的调试消息。 有关详细信息,请参阅 about_CommonParameters。
有效值如下:
- 停止:显示调试消息并停止执行。 将错误写入控制台。
- 查询:显示调试消息并询问是否要继续。 当命令配置为生成调试消息时,将 Debug 公共参数添加到命令中时,会将
$DebugPreference
变量的值更改为 “查询”。 - 继续:显示调试消息并继续执行。
- SilentlyContinue: (默认) 无效。 不会显示调试消息,并且继续执行而不会中断。
示例
以下示例演示在命令行中输入命令时Write-Debug
更改 的值$DebugPreference
的效果。
此更改会影响所有调试消息,包括 cmdlet 和脚本生成的消息。 这些示例演示 Debug 参数,该参数显示或隐藏与单个命令相关的调试消息。
此示例显示了变量的默认值 SilentlyContinue 的效果$DebugPreference
。 默认情况下, Write-Debug
不会显示 cmdlet 的调试消息,并且将继续处理。 使用 Debug 参数时,它会替代单个命令的首选项。 系统会提示用户进行确认。
$DebugPreference
SilentlyContinue
Write-Debug -Message "Hello, World"
Write-Debug -Message "Hello, World" -Debug
DEBUG: Hello, World
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
[?] Help (default is "Y"):
此示例显示了 具有 Continue 值的效果$DebugPreference
。 将显示调试消息,命令将继续处理。
$DebugPreference = "Continue"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World
此示例使用值为 的 $false
Debug 参数来禁止显示单个命令的消息。 不显示调试消息。
Write-Debug -Message "Hello, World" -Debug:$false
此示例演示设置为 Stop 值的效果$DebugPreference
。 将显示调试消息并停止命令。
$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"
此示例使用值为 的 $false
Debug 参数来禁止显示单个命令的消息。 不会显示调试消息,也不会停止处理。
Write-Debug -Message "Hello, World" -Debug:$false
此示例演示设置为“查询”值的效果$DebugPreference
。 将显示调试消息,并提示用户进行确认。
$DebugPreference = "Inquire"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
[?] Help (default is "Y"):
此示例使用值为 的 $false
Debug 参数来禁止显示单个命令的消息。 不会显示调试消息,并且继续处理。
Write-Debug -Message "Hello, World" -Debug:$false
$ErrorActionPreference
确定 PowerShell 如何响应非终止错误,该错误不会停止 cmdlet 处理。 例如,在命令行或脚本、cmdlet 或提供程序中,例如 cmdlet 生成的 Write-Error
错误。
可以使用 cmdlet 的 ErrorAction 通用参数替代特定命令的首选项。
有效值如下:
- 停止:显示错误消息并停止执行。
- 查询:显示错误消息并询问是否要继续。
- 继续: (默认) 显示错误消息并继续执行。
- 暂停:自动挂起工作流作业以允许进一步调查。 调查后,可以恢复工作流。
- SilentlyContinue:无效果。 不会显示错误消息,并且继续执行而不会中断。
- 忽略:取消显示错误消息并继续执行命令。 Ignore 值适用于按命令使用,而不是用作保存的首选项。 Ignore 不是变量的有效值
$ErrorActionPreference
。
$ErrorActionPreference
和 ErrorAction 参数不会影响 PowerShell 响应停止 cmdlet 处理的终止错误的方式。 有关 ErrorAction 通用参数的详细信息,请参阅 about_CommonParameters。
示例
这些示例演示变量的不同值 $ErrorActionPreference
的效果。 ErrorAction 参数用于替代$ErrorActionPreference
值。
此示例显示 $ErrorActionPreference
默认值 Continue。 生成非终止错误。 将显示消息并继续处理。
PS> $ErrorActionPreference = "Continue"
PS> # Display the value of the preference.
PS> $ErrorActionPreference
Continue
PS> # Generate a non-terminating error.
PS> Write-Error -Message "Hello, World"
Write-Error -Message "Hello, World" : Hello, World
+ CategoryInfo : NotSpecified: (:) [Write-Error],WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
PS> # The error message is displayed and execution continues.
PS> # Use the ErrorAction parameter with a value of "SilentlyContinue".
PS> Write-Error -Message "Hello, World" -ErrorAction:SilentlyContinue
PS> # The error message isn't displayed and execution continues.
此示例显示设置为 $ErrorActionPreference
SilentlyContinue 的 。
禁止显示错误消息。
PS> # Display the value of the preference
PS> $ErrorActionPreference = "SilentlyContinue"
PS> # Generate an error message
PS> Write-Error -Message "Hello, World"
PS> # Error message is suppressed
PS> # Use the ErrorAction parameter with a value of "Continue"
PS> Write-Error -Message "Hello, World" -ErrorAction:Continue
Write-Error -Message "Hello, World" -ErrorAction:Continue : Hello, World
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
此示例显示了实际错误的效果。 在本例中, 命令获取不存在的文件 nofile.txt
。
PS> # Display the value of the preference.
PS> $ErrorActionPreference
SilentlyContinue
PS> Get-ChildItem -Path C:\nofile.txt
PS> # Error message is suppressed.
PS> # Change the value to Continue.
PS> $ErrorActionPreference = "Continue"
PS> 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
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem],
ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.
GetChildItemCommand
PS> # Use the ErrorAction parameter
PS> Get-ChildItem -Path C:\nofile.txt -ErrorAction SilentlyContinue
PS> # Error message is suppressed.
PS> # Change the value to Inquire.
PS> $ErrorActionPreference = "Inquire"
PS> Get-ChildItem -Path C:\nofile.txt
Confirm
Cannot find path 'C:\nofile.txt' because it does not exist.
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
[?] Help (default is "Y"): Y
Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path C:\nofile.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem],
ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.
GetChildItemCommand
PS> # Change the value to Continue.
PS> $ErrorActionPreference = "Continue"
PS> # Use the ErrorAction parameter to override the preference value.
PS> Get-Childitem C:\nofile.txt -ErrorAction "Inquire"
Confirm
Cannot find path 'C:\nofile.txt' because it does not exist.
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
[?] Help (default is "Y"): Y
Get-Childitem : Cannot find path 'C:\nofile.txt' because it does not exist.
At line:1 char:1
+ Get-Childitem C:\nofile.txt -ErrorAction "Inquire"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem],
ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.
GetChildItemCommand
$ErrorView
确定 PowerShell 中错误消息的显示格式。
有效值如下:
NormalView: (默认) 为大多数用户设计的详细视图。 由错误说明和错误中涉及的对象的名称组成。
CategoryView:专为生产环境设计的简洁结构化视图。 其格式如下所示:
{Category}: ({TargetName}:{TargetType}) :[{Activity}], {Reason}
有关 CategoryView 中字段的详细信息,请参阅 ErrorCategoryInfo 类。
示例
此示例演示当 的值为 $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。
以下命令采用与错误数组、元素 0 中最新错误关联的 ErrorRecord 对象,并在列表中设置所有错误对象的属性的格式。
$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-Service
和 Group-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...
与 Wrap 参数一起使用Format-Table
以显示服务列表。
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
。 Write-Information
已在 PowerShell 5.0 中引入。
有效值如下:
- 停止:在命令出现
Write-Information
时停止命令或脚本。 - 查询:显示你在命令中指定的
Write-Information
信息性消息,然后询问是否要继续。 - 继续:显示信息性消息,并继续运行。
- 挂起:执行命令后
Write-Information
自动挂起工作流作业,以允许用户在继续之前查看消息。 用户可以自行决定恢复工作流。 - SilentlyContinue: (默认) 无效。 不会显示信息性消息,并且脚本会继续,而不会中断。
$Log*事件
Log*事件首选项变量确定在 事件查看器 中写入 PowerShell 事件日志的事件类型。 默认情况下,仅记录引擎和提供程序事件。 但是,可以使用 Log*事件 首选项变量来自定义日志,例如记录有关命令的事件。
Log*事件首选项变量如下所示:
$LogCommandHealthEvent
:记录命令初始化和处理中的错误和异常。 默认值为$false
(未记录) 。$LogCommandLifecycleEvent
:记录命令发现中的命令和命令管道的启动和停止以及安全异常。 默认值为$false
(未记录) 。$LogEngineHealthEvent
:记录会话的错误和失败。 默认值为$true
(记录) 。$LogEngineLifecycleEvent
:记录会话的开始和结束。 默认值为$true
(记录) 。$LogProviderHealthEvent
:记录提供程序错误,例如读取和写入错误、查找错误和调用错误。 默认值为$true
(记录) 。$LogProviderLifecycleEvent
:添加和删除 PowerShell 提供程序的日志。 默认值为$true
(记录) 。 有关 PowerShell 提供程序的信息,请参阅 about_Providers。
若要启用 Log*事件,请键入值为 的 $true
变量,例如:
$LogCommandLifeCycleEvent = $true
若要禁用事件类型,请键入值为 的 $false
变量,例如:
$LogCommandLifeCycleEvent = $false
启用的事件仅对当前 PowerShell 控制台有效。 若要将配置应用到所有控制台,请将变量设置保存在 PowerShell 配置文件中。 有关详细信息,请参阅 about_Profiles。
$MaximumAliasCount
确定 PowerShell 会话中允许的别名数。 默认值为 4096 ,这应该足以用于大多数用途。 可以根据需要进行调整 $MaximumAliasCount
。
有效值:1024 - 32768 (Int32
)
默认值:4096
若要对系统上的别名进行计数,请键入:
(Get-Alias).count
$MaximumDriveCount
确定给定会话中允许多少个 PowerShell 驱动器。 例如,由 PowerShell 提供程序公开并显示为驱动器的文件系统驱动器和数据存储,例如 Alias:
和 HKLM:
驱动器。
有效值:1024 - 32768 (Int32
)
默认值:4096
若要对系统上的别名进行计数,请键入:
(Get-PSDrive).count
$MaximumErrorCount
确定会话的错误历史记录中保存的错误数。
有效值:256 - 32768 (Int32
)
默认值:256
表示每个保留错误的 对象存储在自动变量中 $Error
。 $Error
包含错误记录对象的数组。 最近的错误是数组 $Error[0]
中的第一个对象。
若要计算系统上的错误,请使用 $Error
数组的 Count 属性。
$Error.count
若要显示特定错误,请使用 [0]
数组表示法查看最新错误。
$Error[0]
若要显示最早的保留错误,请键入:
$Error[($Error.Count -1]
Force 参数替代 ErrorRecord 对象的特殊格式并还原为传统格式。 若要显示 ErrorRecord 对象的属性,请键入以下命令:
$Error[0] | Format-List -Property * -Force
在此示例中, $Error.Count
显示错误数。 若要从错误历史记录中删除所有错误,请使用 Clear
错误数组的 方法。
$Error.Count
17
$Error.Clear()
$Error.Count
0
若要查找错误数组的所有属性和方法,请使用 Get-Member
cmdlet 及其 InputObject 参数。 使用 InputObject 参数时, Get-Member
显示集合的属性和方法。
Get-Member -InputObject $Error
将对象的集合通过管道传递给 Get-Member
时 Get-Member
,将显示集合中对象的属性和方法。
$Error | Get-Member
$MaximumFunctionCount
确定给定会话中允许的函数数。
有效值:1024 - 32768 (Int32
)
默认值:4096
若要查看会话中的函数,请使用 PowerShell Function:
提供程序公开的 PowerShell Function
驱动器。 有关提供程序的详细信息 Function
, about_Function_Provider。
若要列出当前会话中的函数,请键入:
Get-ChildItem Function:
若要对当前会话中的函数进行计数,请键入:
(Get-ChildItem Function:).Count
$MaximumHistoryCount
确定当前会话的命令历史记录中保存的命令数。
有效值:1 - 32768 (Int32
)
默认值:4096
若要确定命令历史记录中当前保存的命令数,请键入:
(Get-History).Count
若要查看会话历史记录中保存的命令,请使用 Get-History
cmdlet。 有关详细信息,请参阅 about_History。
$MaximumVariableCount
确定给定会话中允许的变量数,包括自动变量、首选项变量和在命令和脚本中创建的变量。
有效值:1024 - 32768 (Int32
)
默认值:4096
若要查看会话中的变量,请使用 Get-Variable
cmdlet 以及 PowerShell 驱动器和 PowerShell Variable:
Variable
提供程序的功能。 有关信息,请参阅 about_Variable_Provider。
若要查找系统上的当前变量数,请键入:
(Get-Variable).Count
$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 在向其他应用程序发送文本时使用的字符编码方法。
例如,如果应用程序将 Unicode 字符串返回到 PowerShell,则可能需要将值更改为 UnicodeEncoding 才能正确发送字符。
有效值如下所示:派生自 Encoding 类的对象,例如 ASCIIEncoding、 SBCSCodePageEncoding、 UTF7Encoding、 UTF8Encoding、 UTF32Encoding 和 UnicodeEncoding。
默认值:ASCIIEncoding 对象 (System.Text.ASCIIEncoding)
示例
此示例演示如何使 Windows findstr.exe 命令在已针对使用 Unicode 字符(如中文)的语言进行本地化的计算机上在 PowerShell 中正常工作。
第一个命令查找 的值 $OutputEncoding
。 由于 值是编码对象,因此仅显示其 EncodingName 属性。
$OutputEncoding.EncodingName
在此示例中, findstr.exe 命令用于搜索文件中存在的 Test.txt
两个中文字符。 在 Windows 命令提示符 (cmd.exe) 中运行 此findstr.exe命令 时, findstr.exe 查找文本文件中的字符。 但是,在 PowerShell 中运行同 一findstr.exe 命令时,找不到这些字符,因为 PowerShell 会将它们发送到 ASCII 文本 中的findstr.exe ,而不是 Unicode 文本中。
findstr <Unicode-characters>
若要使命令在 PowerShell 中正常工作,请将 的值 $OutputEncoding
设置为控制台的 OutputEncoding 属性的值,该值基于为 Windows 选择的区域设置。 由于 OutputEncoding 是控制台的静态属性,因此请在命令中使用双冒号 (::
) 。
$OutputEncoding = [console]::OutputEncoding
$OutputEncoding.EncodingName
OEM United States
更改编码后, findstr.exe 命令将查找 Unicode 字符。
findstr <Unicode-characters>
test.txt: <Unicode-characters>
$ProgressPreference
确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的进度更新,例如 Write-Progress cmdlet 生成的进度栏。 cmdlet Write-Progress
创建显示命令状态的进度栏。
有效值如下:
- 停止:不显示进度栏。 而是显示错误消息并停止执行。
- 查询:不显示进度栏。 提示输入继续权限。 如果使用 或
A
进行答复Y
,则会显示进度栏。 - 继续: (默认) 显示进度栏并继续执行。
- SilentlyContinue:执行命令,但不显示进度栏。
$PSEmailServer
指定用于发送电子邮件的默认电子邮件服务器。 此首选项变量由发送电子邮件的 cmdlet 使用,例如 Send-MailMessage cmdlet。
$PSDefaultParameterValues
指定 cmdlet 和高级函数的参数的默认值。
的值 $PSDefaultParameterValues
是一个哈希表,其中键由 cmdlet 名称和参数名称组成,由冒号分隔 (:
) 。 该值是指定的自定义默认值。
$PSDefaultParameterValues
已在 PowerShell 3.0 中引入。
有关此首选项变量的详细信息,请参阅 about_Parameters_Default_Values。
$PSModuleAutoloadingPreference
在会话中启用和禁用模块的自动导入。 所有 为默认值。 无论变量的值如何,都可以使用 Import-Module 导入模块。
有效值为:
- 全部:模块在首次使用时自动导入。 若要导入模块,请获取或使用模块中的任何命令。 例如,使用
Get-Command
。 - ModuleQualified:仅当用户在模块中使用命令的模块限定名称时,才会自动导入模块。 例如,如果用户键入
MyModule\MyCommand
,PowerShell 将导入 MyModule 模块。 - 无:会话中禁用模块的自动导入。 若要导入模块,请使用
Import-Module
cmdlet。
有关模块自动导入的详细信息,请参阅 about_Modules。
$PSSessionApplicationName
指定远程命令的默认应用程序名称,该命令使用 Web Services 进行管理 (WS-Management) 技术。 有关详细信息,请参阅 关于 Windows 远程管理。
系统默认应用程序名称为 WSMAN
,但可以使用此首选项变量更改默认值。
应用程序名称是连接 URI 中的最后一个节点。 例如,以下示例 URI 中的应用程序名称为 WSMAN
。
http://Server01:8080/WSMAN
当远程命令未指定连接 URI 或应用程序名称时,将使用默认应用程序名称。
WinRM 服务使用应用程序名称来选择一个侦听器来为连接请求提供服务。 参数的值应与远程计算机上侦听器的 URLPrefix 属性值匹配。
若要替代系统默认值和此变量的值,并为特定会话选择其他应用程序名称,请使用 New-PSSession、Enter-PSSession 或 Invoke-Command cmdlet 的 ConnectionURI 或 ApplicationName 参数。
首选项 $PSSessionApplicationName
变量在本地计算机上设置,但它指定远程计算机上的侦听器。 如果指定的应用程序名称在远程计算机上不存在,则用于建立会话的命令将失败。
$PSSessionConfigurationName
指定用于在当前会话中创建 的 PSSession 的默认会话配置。
此首选项变量在本地计算机上设置,但它指定位于远程计算机上的会话配置。
变量的值 $PSSessionConfigurationName
是完全限定的资源 URI。
默认值 https://schemas.microsoft.com/PowerShell/microsoft.PowerShell
指示远程计算机上的 Microsoft.PowerShell 会话配置。
如果仅指定配置名称,则会在前面添加以下架构 URI:
https://schemas.microsoft.com/PowerShell/
可以使用 、 Enter-PSSession
或 Invoke-Command
cmdlet 的 ConfigurationName 参数New-PSSession
替代默认值并为特定会话选择不同的会话配置。
可以随时更改此变量的值。 执行此操作时,请记住,所选的会话配置必须存在于远程计算机上。 否则,用于创建使用会话配置的会话的命令将失败。
此首选项变量不能确定在远程用户创建连接到此计算机的会话时使用哪些本地会话配置。 但是,可以使用本地会话配置的权限来确定哪些用户可以使用它们。
$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_Remote 和 about_PSSessions。
若要更改首选项变量的值 $PSSessionOption
,请使用 New-PSSessionOption
cmdlet 创建具有首选选项值的 PSSessionOption 对象。 将输出保存在名为 的 $PSSessionOption
变量中。
$PSSessionOption = New-PSSessionOption -NoCompression
$PSSessionOption
若要在每个 PowerShell 会话中使用首选项变量,请将创建New-PSSessionOption
变量的$PSSessionOption
命令添加到 PowerShell 配置文件。 有关详细信息,请参阅 about_Profiles。
可以为特定远程会话设置自定义选项。 设置的选项优先于系统默认值和首选项变量的值 $PSSessionOption
。
若要设置自定义会话选项,请使用 New-PSSessionOption
cmdlet 创建 PSSessionOption 对象。 然后,使用 PSSessionOption 对象作为创建会话的 cmdlet 中 SessionOption 参数的值,例如 New-PSSession
、 Enter-PSSession
和 Invoke-Command
。
$VerbosePreference
确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的详细消息,例如 Write-Verbose cmdlet 生成的消息。 详细消息描述为执行命令而执行的操作。
默认情况下,不会显示详细消息,但可以通过更改 的值 $VerbosePreference
来更改此行为。
可以使用 cmdlet 的 Verbose 通用参数来显示或隐藏特定命令的详细消息。 有关详细信息,请参阅 about_CommonParameters。
有效值如下:
- 停止:显示详细消息和错误消息,然后停止执行。
- 查询:显示详细消息,然后显示询问是否要继续的提示。
- 继续:显示详细消息,然后继续执行。
- SilentlyContinue: (默认) 不显示详细消息。 继续执行。
示例
这些示例演示 的不同值 $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
此示例显示了 查询 值的效果。 变量 $VerbosePreference
设置为 “查询”。 将显示消息,并提示用户进行确认。
$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 [S] Suspend
[?] Help (default is "Y"):
此示例使用 Verbose 参数,其值为 $false
替代 查询 值。 系统不会提示用户,也不会显示消息。
Write-Verbose -Message "Verbose message test." -Verbose:$false
$WarningPreference
确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的警告消息,例如 Write-Warning cmdlet 生成的消息。
默认情况下,将显示警告消息并继续执行,但可以通过更改 的值 $WarningPreference
来更改此行为。
可以使用 cmdlet 的 WarningAction 通用参数来确定 PowerShell 如何响应来自特定命令的警告。 有关详细信息,请参阅 about_CommonParameters。
有效值如下:
- 停止:显示警告消息和错误消息,然后停止执行。
- 查询:显示警告消息,然后提示继续权限。
- 继续: (默认) 显示警告消息,然后继续执行。
- SilentlyContinue:不显示警告消息。 继续执行。
示例
这些示例显示了 的不同值 $WarningPreference
的效果。
WarningAction 参数替代首选项值。
此示例显示默认值 Continue 的效果。
$m = "This action can delete data."
Write-Warning -Message $m
WARNING: This action can delete data.
此示例使用值为 SilentlyContinue 的 WarningAction 参数来禁止显示警告。 不会显示该消息。
$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
变量更改为 “查询 ”值。 系统会提示用户进行确认。
$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 [S] Suspend
[?] Help (default is "Y"):
此示例使用值为 SilentlyContinue 的 WarningAction 参数。 该命令将继续执行,并且不显示任何消息。
$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
此示例使用具有“查询”值的 WarningAction。 出现警告时,系统会提示用户。
$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 [S] Suspend
[?] Help (default is "Y"):
$WhatIfPreference
确定是否为支持它的每个命令自动启用 WhatIf 。 启用 WhatIf 后,cmdlet 将报告命令的预期效果,但不执行该命令。
有效值如下:
- false (0,未启用) : (默认) WhatIf 不会自动启用。 若要手动启用它,请使用 cmdlet 的 WhatIf 参数。
- true (1,已启用) : 支持 WhatIf 的任何命令上自动启用。 用户可以使用值为 False 的 WhatIf 参数手动禁用它,例如
-WhatIf:$false
。
示例
这些示例显示了 的不同值 $WhatIfPreference
的效果。
它们演示如何使用 WhatIf 参数替代特定命令的首选项值。
此示例演示设置为默认值 False 的$WhatIfPreference
变量的效果。 使用 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
此示例显示设置为值 True 的$WhatIfPreference
变量的效果。 使用 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 时删除文件。 它使用值为 的 $false
WhatIf 参数。 使用 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
下面是不支持 WhatIf 且Stop-Process
支持 WhatIf 的 cmdlet 示例。Get-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
支持 WhatIf。 Winword 进程不会停止。
Stop-Process -Name Winword
What if: Performing the operation "Stop-Process" on target "WINWORD (15024)".
可以使用值为 的 $false
WhatIf 参数来替代 Stop-Process
WhatIf 行为。 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