(23)Powershell中的首选项变量

    上一节介绍了 Powershell 中的环境变量,本节介绍 Powershell 中的首选项变量,这些变量的做用与环境变量相似,都是Powershell中的内置变量,也能够对这些值进行更改。须要注意的是,首选项变量影响 PowerShell 操做环境以及在该环境中运行的全部命令。在不少状况下,cmdlet 带有的参数可用于替代特定命令的首选行为。shell


    如下是 Powershell 中常见的首选项变量及其默认值。
数组

首选项变量 默认值及说明
$ConfirmPreference  High
$DebugPreference SilentlyContinue
$ErrorActionPreference  Continue
$ErrorView NormalView
$FormatEnumerationLimit 4
$LogCommandHealthEvent False(不写入日志),记录命令初始化和进行处理时产生的错误和异常
$LogCommandLifecycleEvent False(不写入日志),记录命令和命令管道的启动和中止,以及命令发现过程当中的安全异常。
$LogEngineHealthEvent True(写入日志),记录会话的错误和故障。
$LogEngineLifecycleEvent True(写入日志),记录会话的打开和关闭。
$LogProviderLifecycleEvent True(写入日志),记录添加和删除 Windows PowerShell 提供程序。
$LogProviderHealthEvent True(写入日志),记录提供程序错误,如读写错误、查找错误以及调用错误。
$MaximumAliasCount 4096,肯定在 Windows PowerShell 会话中容许多少个别名。可使用命令 (get-alias).count 统计别名数量。
$MaximumDriveCount 4096,肯定在给定的会话中,容许多少个 Windows PowerShell 驱动器。可使用命令 (get-psdrive).count统计数量。
$MaximumErrorCount 256,肯定在会话的错误历史记录中保存多少个错误。$Error[0]是最新的错误信息。
$MaximumFunctionCount 4096,肯定给定会话中容许多少个函数。可使用

(get-childitem function:).count 统计当前会话中的函数个数。安全

$MaximumHistoryCount 64,肯定当前会话的命令历史记录中保存多少条命令。
$MaximumVariableCount 4096,肯定给定会话中容许多少个变量,包括自动变量、首选项变量以及在命令和脚本中建立的变量。
$OFS ""(空格字符),输出字段分隔符。指定在数组转换为字符串时,用来分隔数组元素的字符。
$OutputEncoding ASCIIEncoding,PowerShell 在将文本发送给其余应用程序时,所使用的字符编码方法。
$ProgressPreference Continue,显示操做执行的进度条,并继续执行。
$PSEmailServer (无)指定用于发送电子邮件的默认电子邮件服务器。
$PSSessionApplicationName WSMAN
$PSSessionConfigurationName http://schemas.microsoft.com/powershell/microsoft.powershell   指定使用 WS-Management 技术的远程命令的默认应用程序名称。
$VerbosePreference SilentlyContinue, 默认不显示命令操做的详细消息。继续执行。
$WarningPreference Continue,默认显示操做执行的警告消息,而后继续执行。
$WhatIfPreference 0,默认不自动启用 WhatIf。若要手动启用它,请使用命令的 WhatIf 参数。

    以上列出的是常见的首选项及其默认值,若是要查看所有的首选项变量,输入命令 Get-Variable 进行查看。服务器


  1. 首选项命令值的查看与更改ide

    若是要查看某个具体的首选项的值,直接输入首选项变量的名称。例如函数

PS C:\> $ConfirmPreference
High

    若是要更改首选项变量的值,使用赋值语句,例如:ui

PS C:\> $ConfirmPreference = "Medium"
PS C:\> $ConfirmPreference
Medium

    须要注意的是,首选项变量与其余变量同样,在当前回话对值所作的更改,只针对当前窗口(会话)有效。若是须要使更改永久有效,须要把更改写入 Powershell 配置文件中。另外,Powershell 中的首选项每每有指定的可选值,即只能把可选值中的一个赋值给该变量,而不是能够赋值任何值。如下会对每一个首选项变量作详细说明以及其全部的可选值。
编码


2. $ConfirmPreferencespa

    根据命令的名称可知,该命令与确认(Confirm)有关。Powershell 对每个命令执行结果可能产生的影响划分了一个等级(High、Medium、Low 或 None),也就是对每个命令都划分了风险(对当前系统可能产生的影响)等级。
命令行

    若是 $ConfirmPreference 值(High、Medium、Low 或 None)大于等于命令操做的风险(High、Medium、Low 或 None)时,PowerShell 会在执行该操做以前自动请求用户确认(告诉你输入的命令可能存在风险,是否要继续执行)。

    $ConfirmPreference 有如下有效可选值。

有效可选值
说明
None 不自动确认任何 cmdlet 操做。用户必须使用 Confirm 参数来请求确认特定命令。即Powershell认为你输入的每一条命令都有可能存在风险,每条命令都须要明确确认
Low 对命令风险等级为低、中或高的命令操做自动提示确认。若是要阻止特定命令提示确认,可使用通用参数 -Confirm:$false。
Medium 对命令风险等级为中或高的命令操做自动提示确认。若是要为特定命令启用提示确认,可使用 -confirm。若是要阻止特定命令提示确认,请使用 confirm:$false。
High 默认值。对命令等级为高风险的命令操做自动提示确认。若是要为特定命令启用提示确认,可使用 -confirm。若是要阻止特定命令提示确认,请使用 -confirm:$false。

    哪些行为在Powershell中会被认定为有风险行为?好比删除文件,停掉全部的Service,命令执行须要占用大量系统资源等。例如:

PS C:\> $ConfirmPreference
Medium
PS C:\> cd D:\MyPowerShell
PS D:\MyPowerShell> Remove-Item .\Test.ps1
确认
是否确实要执行此操做?
对目标“D:\MyPowerShell\Test.ps1”执行操做“删除文件”。
[Y] 是(Y)  [A] 全是(A)  [N] 否(N)  [L] 全否(L)  [S] 挂起(S)  [?] 帮助 (默认值为“Y”):

    在上面的例子中 $ConfirmPreference 的值为"Medium"。须要注意的是,Powershell中的大部分命令的风险等级为"Medium",而$ConfirmPreference 的默认值时"High",因此在大部分的时候,并不会自动提示。若是须要要激活自动提示,能够将$ConfirmPreference的值更改成"Medium"或者"Low"。


3. $DebugPreference

    从命令的名称可知,与调试(Debug)有关。Powershell 根据该值,确认如何对待调试信息(脚本、cmdlet 或提供程序生成的调试消息,或者 Write-Debug 命令在命令行上生成的调试消息)-是忽略仍是继续执行。有如下可选值:

有效可选值 说明
Stop 显示调试信息并中止命令的执行,并把错误输出到控制台。
Inquire 显示调试信息,并和你确认是否要继续执行。
Continue 显示调试信息,并继续执行。
SilentlyContinue 默认值。不显示调试信息,继续执行不发生中断,至关于直接忽视调试信息。若是要强制显示调试信息,请使用 -Debug 参数。

    调试信息一般是对开发人员有效,具备比较强的专业性(其余人看了也是一脸懵逼^_^),因此默认状况下不显示调试信息。例如例子说明了SilentlyContinue的做用:

PS C:\> $DebugPreference
SilentlyContinue
PS C:\> Write-Debug "This is debug message"
PS C:\> Write-Debug "This is debug message" -Debug
调试: This is debug message
确认
是否继续执行此操做?
[Y] 是(Y)  [A] 全是(A)  [H] 终止命令(H)  [S] 挂起(S)  [?] 帮助 (默认值为“Y”):

    如下示例说明了其余3个参数的用法及所表明的含义:

PS C:\> $DebugPreference = "Continue"
PS C:\> $DebugPreference
Continue
PS C:\> Write-Debug "This is debug message"
调试: This is debug message
PS C:\> Write-Debug "This is debug message" -Debug:$false
PS C:\> $DebugPreference = "Stop"
PS C:\> $DebugPreference
Stop
PS C:\> Write-Debug "This is debug message"
调试: This is debug message
Write-Debug : 已中止执行命令,由于首选项变量“DebugPreference”或通用参数被设置为 Stop。
所在位置 行:1 字符: 12
+ Write-Debug <<<<  "This is debug message"
    + CategoryInfo          : OperationStopped: (:) [Write-Debug], ParentContainsErrorReco
    + FullyQualifiedErrorId : ActionPreferenceStop,Microsoft.PowerShell.Commands.WriteDebu
PS C:\> Write-Debug "This is debug message" -Debug:$false
PS C:\> $DebugPreference = "Inquire"
PS C:\> Write-Debug "This is debug message"
调试: This is debug message
确认
是否继续执行此操做?
[Y] 是(Y)  [A] 全是(A)  [H] 终止命令(H)  [S] 挂起(S)  [?] 帮助 (默认值为“Y”): PS C:\>
PS C:\> Write-Debug "This is debug message" -Debug:$false
PS C:\>

    经过以上示例可知,对于任何调试信息均可以经过 -Debug:$false 或者 -Debug:$true 来阻止或是激活调试信息。


4. $ErrorActionPreference

    $ErrorActionPreference 与 $DebugPreference 很是相似,只是前者是用来处理错误信息,而不是调试信息。Powershell 根据 $ErrorActionPreference 的值,肯定如何响应命令行、脚本、cmdlet 或提供程序中的非终止性错误(不会致使cmdlet 处理中止的错误),如 Write-Error cmdlet 生成的错误。

    $ErrorActionPreference 提供了如下有效可选值:

有效值 说明
Stop 显示错误信息并中止执行
Inquire 显示错误信息,并和你确认是否要继续执行
Continue 默认值显示错误信息并继续执行
SilentlyContinue 不显示错误信息,继续执行不发生中断

    如下示例说明了不一样值的不一样做用。

PS C:\> $ErrorActionPreference
Continue
PS C:\> Write-Error "This is error message"
Write-Error "This is error message" : This is error message
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
PS C:\> Write-Error "This is error message" -ErrorAction:SilentlyContinue
PS C:\>
PS C:\>
PS C:\> $ErrorActionPreference = "SilentlyContinue"
PS C:\> $ErrorActionPreference
SilentlyContinue
PS C:\> Write-Error "This is error message"
PS C:\> Write-Error "This is error message" -ErrorAction:continue
Write-Error "This is error message" -ErrorAction:continue : This is error message
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
PS C:\>
PS C:\>
PS C:\> $ErrorActionPreference
SilentlyContinue
PS C:\> Get-ChildItem -path notExistFile.txt
PS C:\> $ErrorActionPreference = "Continue"
PS C:\> Get-ChildItem -path notExistFile.txt
Get-ChildItem : 找不到路径“C:\notExistFile.txt”,由于该路径不存在。
所在位置 行:1 字符: 14
+ Get-ChildItem <<<<  -path notExistFile.txt
    + CategoryInfo          : ObjectNotFound: (C:\notExistFile.txt:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
PS C:\> Get-ChildItem -path notExistFile.txt -ErrorAction:SilentlyContinue
PS C:\>
PS C:\>
PS C:\> $ErrorActionPreference = "Inquire"
PS C:\> $ErrorActionPreference
Inquire
PS C:\> Get-ChildItem -path notExistFile.txt
确认
找不到路径“C:\notExistFile.txt”,由于该路径不存在。
[Y] 是(Y)  [A] 全是(A)  [H] 终止命令(H)  [S] 挂起(S)  [?] 帮助 (默认值为“Y”):

5. $ErrorView

    Powershell 中错误信息的显示格式。有如下两个可选值:

有效可选值 说明
NormalView 默认值。错误信息的详细视图(View),包括错误描述、错误中所涉及对象的名称,以及指向命令中致使错误的词的箭头 (<<<<)。
CategoryView 错误信息的简明结构化视图。格式为:{Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}

    如下例子说明了错误信息显示格式的不一样:

PS C:\> $ErrorView
NormalView
PS C:\> Get-ChildItem -path notExistFile.txt
Get-ChildItem : 找不到路径“C:\notExistFile.txt”,由于该路径不存在。
所在位置 行:1 字符: 14
+ Get-ChildItem <<<<  -path notExistFile.txt
    + CategoryInfo          : ObjectNotFound: (C:\notExistFile.txt:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
PS C:\> $ErrorView = "CategoryView"
PS C:\> Get-ChildItem -path notExistFile.txt
ObjectNotFound: (C:\notExistFile.txt:String) [Get-ChildItem], ItemNotFoundException

    须要注意的是,ErrorView 的值只影响错误显示;它不会更改存储在 $error 自动变量中的错误对象的结构。

    $error 自动变更变量是包含错误信息的数组,第一个元素(下标为0)包含的是最新的错误信息。例如在上面的语句执行后,error[0]错误信息以下:

PS C:\> $Error[0] | Format-List -Property * -Force
PSMessageDetails      :
Exception             : System.Management.Automation.ItemNotFoundException: 找不到路径“C:\notExistFile.txt”,由于该路
                        径不存在。
                           在 System.Management.Automation.SessionStateInternal.GetChildItems(String path, Boolean recu
                        rse, CmdletProviderContext context)
                           在 System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(String path, Boolean r
                        ecurse, CmdletProviderContext context)
                           在 Microsoft.PowerShell.Commands.GetChildItemCommand.Proce***ecord()
TargetObject          : C:\notExistFile.txt
CategoryInfo          : ObjectNotFound: (C:\notExistFile.txt:String) [Get-ChildItem], ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
PipelineIterationInfo : {0, 1}

6. $FormatEnumerationLimit

    肯定一次显示中包含多少个枚举项(显示多少项)。该变量不会影响基础对象;只影响显示。当$FormatEnumerationLimit 的值小于枚举项的数量时,PowerShell  会添加一个省略号(...)来指示还有其余项未显示。有效值:整数 (Int32),默认值:4 。 例如:

PS C:\> $FormatEnumerationLimit
4
PS C:\> Get-Service | Group-Object -Property Status | Format-List
Name   : Stopped
Count  : 62
Group  : {System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController, System.ServiceProcess.Servi
         ceController, System.ServiceProcess.ServiceController...}
Values : {Stopped}
Name   : Running
Count  : 41
Group  : {System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController, System.ServiceProcess.Servi
         ceController, System.ServiceProcess.ServiceController...}
Values : {Running}
PS C:\> $FormatEnumerationLimit = 6
PS C:\> Get-Service | Group-Object -Property Status | Format-List
Name   : Stopped
Count  : 62
Group  : {System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController, System.ServiceProcess.Servi
         ceController, System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController, System.Service
         Process.ServiceController...}
Values : {Stopped}
Name   : Running
Count  : 41
Group  : {System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController, System.ServiceProcess.Servi
         ceController, System.ServiceProcess.ServiceController, System.ServiceProcess.ServiceController, System.Service
         Process.ServiceController...}
Values : {Running}

7. 总结

    这节介绍了 Powershell中的首选项变量,这些变量的做用于环境变量相似,须要注意的是,更改首选项变量不仅针对当前会话,对再次打开的窗体任然有效,这些首选项都提供了默认的参数值,对于刚开始不熟悉的,尽可能不要去更改这些变量的默认值,了解每一个变量的做用便可。

相关文章
相关标签/搜索