(23)Powershell中的首選項變量

    上一節介紹了 Powershell 中的環境變量,本節介紹 Powershell 中的首選項變量,這些變量的作用與環境變量類似,都是Powershell中的內置變量,也可以對這些值進行更改。需要注意的是,首選項變量影響 PowerShell 操作環境以及在該環境中運行的所有命令。在很多情況下,cmdlet 帶有的參數可用於替代特定命令的首選行爲。


    以下是 Powershell 中常見的首選項變量及其默認值。

首選項變量默認值及說明
$ConfirmPreference High
$DebugPreferenceSilentlyContinue
$ErrorActionPreference Continue
$ErrorViewNormalView
$FormatEnumerationLimit4
$LogCommandHealthEventFalse(不寫入日誌),記錄命令初始化和進行處理時產生的錯誤和異常
$LogCommandLifecycleEventFalse(不寫入日誌),記錄命令和命令管道的啓動和停止,以及命令發現過程中的安全異常。
$LogEngineHealthEventTrue(寫入日誌),記錄會話的錯誤和故障。
$LogEngineLifecycleEventTrue(寫入日誌),記錄會話的打開和關閉。
$LogProviderLifecycleEventTrue(寫入日誌),記錄添加和刪除 Windows PowerShell 提供程序。
$LogProviderHealthEventTrue(寫入日誌),記錄提供程序錯誤,如讀寫錯誤、查找錯誤以及調用錯誤。
$MaximumAliasCount4096,確定在 Windows PowerShell 會話中允許多少個別名。可以使用命令 (get-alias).count 統計別名數量。
$MaximumDriveCount4096,確定在給定的會話中,允許多少個 Windows PowerShell 驅動器。可以使用命令 (get-psdrive).count統計數量。
$MaximumErrorCount256,確定在會話的錯誤歷史記錄中保存多少個錯誤。$Error[0]是最新的錯誤信息。
$MaximumFunctionCount4096,確定給定會話中允許多少個函數。可以使用

(get-childitem function:).count 統計當前會話中的函數個數。

$MaximumHistoryCount64,確定當前會話的命令歷史記錄中保存多少條命令。
$MaximumVariableCount4096,確定給定會話中允許多少個變量,包括自動變量、首選項變量以及在命令和腳本中創建的變量。
$OFS""(空格字符),輸出字段分隔符。指定在數組轉換爲字符串時,用來分隔數組元素的字符。
$OutputEncodingASCIIEncoding,PowerShell 在將文本發送給其他應用程序時,所使用的字符編碼方法。
$ProgressPreferenceContinue,顯示操作執行的進度條,並繼續執行。
$PSEmailServer(無)指定用於發送電子郵件的默認電子郵件服務器。
$PSSessionApplicationNameWSMAN
$PSSessionConfigurationNamehttp://schemas.microsoft.com/powershell/microsoft.powershell   指定使用 WS-Management 技術的遠程命令的默認應用程序名稱。
$VerbosePreferenceSilentlyContinue, 默認不顯示命令操作的詳細消息。繼續執行。
$WarningPreferenceContinue,默認顯示操作執行的警告消息,然後繼續執行。
$WhatIfPreference0,默認不自動啓用 WhatIf。若要手動啓用它,請使用命令的 WhatIf 參數。

    以上列出的是常見的首選項及其默認值,如果要查看全部的首選項變量,輸入命令 Get-Variable 進行查看。


  1. 首選項命令值的查看與更改

    如果要查看某個具體的首選項的值,直接輸入首選項變量的名稱。例如

PS C:\> $ConfirmPreference
High

    如果要更改首選項變量的值,使用賦值語句,例如:

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

    需要注意的是,首選項變量與其他變量一樣,在當前回話對值所做的更改,只針對當前窗口(會話)有效。如果需要使更改永久有效,需要把更改寫入 Powershell 配置文件中。另外,Powershell 中的首選項往往有指定的可選值,即只能把可選值中的一個賦值給該變量,而不是可以賦值任何值。以下會對每個首選項變量做詳細說明以及其所有的可選值。


2. $ConfirmPreference

    根據命令的名稱可知,該命令與確認(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中的首選項變量,這些變量的作用於環境變量類似,需要注意的是,更改首選項變量不只針對當前會話,對再次打開的窗體任然有效,這些首選項都提供了默認的參數值,對於剛開始不熟悉的,儘量不要去更改這些變量的默認值,瞭解每個變量的作用即可。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章