(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中的首選項變量,這些變量的做用於環境變量相似,須要注意的是,更改首選項變量不僅針對當前會話,對再次打開的窗體任然有效,這些首選項都提供了默認的參數值,對於剛開始不熟悉的,儘可能不要去更改這些變量的默認值,瞭解每一個變量的做用便可。

相關文章
相關標籤/搜索