about_Preference_Variables

適用於: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0, Windows PowerShell 5.0

主題

喜好設定變數

簡短描述

可自訂 Windows PowerShell 行為的變數

詳細描述

Windows PowerShell 包含一組可讓您自訂其行為的變數。這些「喜好設定變數」的作用如同以 GUI 為基礎的系統中的選項。

喜好設定變數會影響 Windows PowerShell 作業環境以及在環境中執行的所有命令。在許多情況下,Cmdlet 有一些參數,您可用來覆寫特定命令的喜好設定行為。

下表列出喜好設定變數與其預設值。

    Variable                             Default Value
    --------                             -------------
    $ConfirmPreference                   High
    $DebugPreference                     SilentlyContinue
    $ErrorActionPreference               Continue
    $ErrorView                           NormalView
    $FormatEnumerationLimit              4
    $LogCommandHealthEvent               False (not logged)
    $LogCommandLifecycleEvent            False (not logged)
    $LogEngineHealthEvent                True (logged)
    $LogEngineLifecycleEvent             True (logged)
    $LogProviderLifecycleEvent           True (logged)
    $LogProviderHealthEvent              True (logged)
    $MaximumAliasCount                   4096
    $MaximumDriveCount                   4096
    $MaximumErrorCount                   256
    $MaximumFunctionCount                4096
    $MaximumHistoryCount                 4096
    $MaximumVariableCount                4096
    $OFS                                 (Space character (" "))
    $OutputEncoding                      ASCIIEncoding object
    $ProgressPreference                  Continue
    $PSDefaultParameterValues            (None - empty hash table)     
    $PSEmailServer                       (None)
    $PSModuleAutoLoadingPreference       All
    $PSSessionApplicationName            WSMAN
    $PSSessionConfigurationName          https://schemas.microsoft.com/PowerShell/microsoft.PowerShell 
    $PSSessionOption                     (See below)
    $VerbosePreference                   SilentlyContinue
    $WarningPreference                   Continue
    $WhatIfPreference                    0

Windows PowerShell 也包含下列可儲存使用者喜好設定的環境變數。如需有關這些環境變數的詳細資訊,請參閱 about_Environment_Variables。

    Variable                                         
    --------    
    PSExecutionPolicyPreference                     
    PSModulePath                        

使用喜好設定變數

本文將說明每個喜好設定變數。

若要顯示特定喜好設定變數的目前值,請輸入變數的名稱。Windows PowerShell 會在回應中提供其值。例如,下列命令會顯示 $ConfirmPreference 變數的值。

        PS> $ConfirmPreference
        High

若要變更變數的值,請使用指派陳述式。例如,下列陳述式會將值 "Medium" 指派給 $ConfirmPreference 變數。

        PS> $ConfirmPreference = "Medium"

如同所有的變數,您所設定的值專屬於目前的 Windows PowerShell 工作階段。若要讓這些值在所有的 Windows PowerShell 工作階段中生效,請將它們加入至您的 Windows PowerShell 設定檔。如需詳細資訊,請參閱 about_Profiles。

從遠端工作

當您在遠端電腦上執行命令時,遠端命令只受制於在遠端電腦上的 Windows PowerShell 用戶端中設定的喜好設定。例如,當您執行遠端命令時,遠端電腦上的 $DebugPreference 變數值可決定 Windows PowerShell 如何回應偵錯訊息。

如需遠端命令的詳細資訊,請參閱 about_remote。

$ConfirmPreference
------------------

決定 Windows PowerShell 是否在執行 Cmdlet 或函式前自動提示您進行確認。

當 $ConfirmPreference 變數的值 (高、中、低) 小於或等於指派給 Cmdlet 或函式的風險 (高、中、低) 時,Windows PowerShell 會在執行 Cmdlet 或函式前自動提示您進行確認。

如果 $ConfirmPreference 變數的值為 [無],Windows PowerShell 永遠不會在執行 Cmdlet 或函式之前自動提示您。

若要變更工作階段中所有 Cmdlet 和函式的確認行為,請變更 $ConfirmPreference 變數的值。

若要覆寫單一命令的 $ConfirmPreference,請使用 Cmdlet 或函式的 Confirm 參數。若要要求確認,請使用 -Confirm。若要隱藏確認,請請使用 -Confirm:$false

$ConfirmPreference 的有效值:

None:Windows PowerShell 不會自動提示。若要要求確認特定命令,請使用 Cmdlet 或函式的 Confirm 參數。

低:Windows PowerShell 會在執行具有高、中、低風險的 Cmdlet 或函式前提示進行確認。

中:Windows PowerShell 會在執行具有中或高風險的 Cmdlet 或函式前提示進行確認。

高:Windows PowerShell 會在執行具有高風險的 Cmdlet 或函式前提示進行確認。

詳細說明

當 Cmdlet 或函式的動作大幅影響系統時 (例如會刪除資料或使用大量系統資源的動作),Windows PowerShell 可在執行動作前自動提示您進行確認。

例如,

    PS> remove-item 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 的值變更為 [中] 或 [低],即可啟動自動確認。

範例

此範例顯示 $ConfirmPreference 的預設值效果。[高] 值只會確認高風險的 Cmdlet 和函式。由於大部分的 Cmdlet 和函式屬於中度風險,所以不會自動確認。

          PS> $confirmpreference              #Get the current value of the
          High                                 variable
          
          PS> remove-item temp1.txt           #Delete a file
          PS>                                 #Deleted without confirmation

           
          PS> remove-item temp2.txt -confirm  #Use the Confirm parameter to
                                               request confirmation

          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 值變更為 [中] 的效果。因為大部分的 Cmdlet 和函式屬於中度風險,所以會自動確認。若要隱藏單一命令的確認提示字元,請使用值為 $false 的 Confirm 參數

            
          PS> $confirmpreference = "Medium"  #Change the value of $ConfirmPreference
          PS> remove-item temp2.txt          #Deleting a file triggers confirmation         
                                     
          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"):


          PS> remove-item temp3.txt -confirm:$false   #Use Confirm parameter
                                                       to suppress confirmation
          PS>

$DebugPreference
------------------

決定 Windows PowerShell 如何回應由指令碼、Cmdlet 或提供者產生的偵錯訊息,或由 Write-Debug 命令在命令列產生的偵錯訊息。

某些 Cmdlet 會顯示偵錯訊息,通常是針對程式設計人員和技術支援專業人員所設計的技術性訊息。根據預設,不會顯示偵錯訊息,但是您可以藉由變更 $DebugPreference 值來顯示偵錯訊息。

您也可以使用 Cmdlet 的 Debug 一般參數來顯示或隱藏特定命令的偵錯訊息。如需詳細資訊,請輸入:"get-help about_commonparameters"。

有效值:

Stop:顯示偵錯訊息並停止執行。將錯誤寫入至主控台。

Inquire:顯示偵錯訊息並詢問您是否要繼續。請注意,如果命令已設定為產生偵錯訊息,將 Debug 一般參數加入至此命令會使 $DebugPreference 變數的值變更為 Inquire。

Continue:顯示偵錯訊息並繼續執行。

SilentlyContinue:(預設值) 沒有作用。不會顯示偵錯訊息並繼續執行而不中斷。

範例

下列範例顯示在命令列輸入 Write-Debug 命令時,變更 $DebugPreference 值的效果。此變更會影響所有偵錯訊息,包括由 Cmdlet 和指令碼所產生的偵錯訊息。這些範例也會顯示如何使用 Debug 一般參數,該參數可顯示或隱藏單一命令的相關偵錯訊息。

此範例顯示預設值 "SilentlyContinue" 的效果。不會顯示偵錯訊息並繼續處理。最後一個命令會使用 Debug 參數來覆寫單一命令的喜好設定。

        PS> $debugpreference                    # Get the current value of
        SilentlyContinue                          $DebugPreference

        PS> write-debug "Hello, World"
        PS>                                     # The debug message is not
                                                  displayed.

        PS> write-debug "Hello, World" -Debug   # Use the Debug parameter
        DEBUG: Hello, World                     # The debug message is
                                                  is requested.                                                                                                    displayed and confirmation
        Confirm
        Continue with this operation?
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

此範例會顯示 "Continue" 值的效果。最後一個命令會使用值為 $false 的 Debug 參數來抑制單一命令的訊息。

        PS> $debugpreference = "Continue"   # Change the value to "Continue"

        PS> write-debug "Hello, World"
        DEBUG: Hello, World                 # The debug message is displayed
        PS>                                   and processing continues.
                                           

        PS> write-debug "Hello, World" -Debug:$false   
                                            # Use the Debug parameter with
                                              false.
        PS>                                 # The debug message is not
                                              displayed.

此範例會顯示 "Stop" 值的效果。最後一個命令會使用值為 $false 的 Debug 參數來抑制單一命令的訊息。

        PS> $debugpreference = "Stop"       #Change the value to "Stop"
        PS> write-debug "Hello, World"
        DEBUG: Hello, World
        Write-Debug : Command execution stopped because the shell variable "DebugPreference" is
        set to Stop.
        At line:1 char:12
        + write-debug  <<<< "Hello, World"

        PS> write-debug "Hello, World" -Debug:$false   
                                            # Use the Debug parameter with
                                              $false
        PS>                                 # The debug message is not 
                                              displayed and processing is
                                              not stopped.

此範例會顯示 "Inquire" 值的效果。最後一個命令會使用值為 $false 的 Debug 參數來抑制單一命令的訊息。

        PS> $debugpreference = "Inquire"
        PS> write-debug "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"):

        PS> write-debug "Hello, World" -Debug:$false   
                                            # Use the Debug parameter with
                                              $false
        PS>                                 # The debug message is not
                                              displayed and processing
                                              continues without interruption.

$ErrorActionPreference
----------------------

決定 Windows PowerShell 如何在命令列或在指令碼、Cmdlet 或提供者中回應非終止錯誤 (不會停止 Cmdlet 處理的錯誤),例如由 Write-Error Cmdlet 所產生的錯誤。

您也可以使用 Cmdlet 的 ErrorAction 一般參數來覆寫特定命令的喜好設定。

有效值:

Stop:顯示錯誤訊息並停止執行。

Inquire:顯示錯誤訊息並詢問您是否要繼續。

Continue (預設值):顯示錯誤訊息並繼續執行。

Suspend:自動暫止工作流程工作,以便進一步調查。經過調查之後,就可以繼續工作流程。

SilentlyContinue:沒有作用。不會顯示錯誤訊息並繼續執行而不中斷。

注意:

ErrorAction 一般參數的 Ignore 值不是有效的 $ErrorActionPreference 變數值。Ignore 值主要提供個別命令使用,而不是當作已儲存的喜好設定使用。

$ErrorActionPreference 和 ErrorAction 一般參數都不會影響 Windows PowerShell 回應終止錯誤 (即停止 Cmdlet 處理的錯誤) 的方式。

如需 ErrorAction 一般參數的詳細資訊,請參閱 about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216)。

範例

以下範例顯示不同 $ErrorActionPreference 值的效果,以及如何使用 ErrorAction 一般參數來覆寫單一命令的喜好設定。ErrorAction 參數具有與 $ErrorActionPreference 變數相同的有效值。

此範例會顯示 Continue 值 (這是預設值) 的效果。

        PS> $erroractionpreference                      
        Continue# Display the value of the preference.          
                                  
        PS> write-error "Hello, World"                  
                                # Generate a non-terminating error.

        write-error "Hello, World" : Hello, World       
                                # The error message is displayed and
                                  execution continues.

        PS> write-error "Hello, World" -ErrorAction:SilentlyContinue
                                # Use the ErrorAction parameter with a 
                                  value of "SilentlyContinue".
        PS>                                             
                                # The error message is not displayed and
                                  execution continues.

此範例會顯示 SilentlyContinue 值的效果。

        PS> $ErrorActionPreference = "SilentlyContinue"
                                # Change the value of the preference.
        PS> write-error "Hello, World"                  
                                # Generate an error message.
        PS>                     
                                # Error message is suppressed.
        PS> write-error "Hello, World" -erroraction:continue
                                # Use the ErrorAction parameter with a
                                  value of "Continue".
        write-error "Hello, World" -erroraction:continue : Hello, World
                                # The error message is displayed and
                                  execution continues.

此範例會顯示真正錯誤的效果。在此案例中,命令會取得不存在的檔案 (nofile.txt)。此範例也會使用 ErrorAction 一般參數來覆寫喜好設定。

        PS> $erroractionpreference                      
        SilentlyContinue        # Display the value of the preference.     
                                

        PS> get-childitem -path nofile.txt
        PS>                     # Error message is suppressed.

        PS> $ErrorActionPreference = "Continue" 
                                # Change the value to Continue.

        PS> get-childitem -path nofile.txt
        Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
        At line:1 char:4
        + get-childitem  <<<< nofile.txt

        PS> get-childitem -path nofile.txt -erroraction SilentlyContinue
                                # Use the ErrorAction parameter
        PS>                     
                                # Error message is suppressed.
  
        PS> $ErrorActionPreference = "Inquire"          
                                # Change the value to Inquire.
        PS> get-childitem -path 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:4
        + get-childitem  <<<< nofile.txt

        PS> $ErrorActionPreference = "Continue"                  
                                # Change the value to Continue.
        PS> Get-Childitem nofile.txt -erroraction "Inquire"      
                                # Use the ErrorAction parameter to override
                                  the preference value.

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

$ErrorView
----------

決定 Windows PowerShell 中錯誤訊息的顯示格式。

有效值

NormalView (預設值):針對大部分使用者設計的詳細檢視。包含錯誤的描述,與錯誤相關的物件名稱,以及指向命令中造成錯誤之文字的箭號 (<<<<)。

CategoryView:針對生產環境而設計的簡潔、結構化檢視。格式如下:{Category}:({TargetName}:{TargetType}):[{Activity}], {Reason}

如需有關 CategoryView 中欄位的詳細資訊,請參閱 Windows PowerShell SDK 中的「ErrorCategoryInfo 類別」。

範例

這些範例會顯示 ErrorView 值的效果。

此範例會顯示當 $ErrorView 值為 NormalView 時,錯誤出現的方式。在此情況下,Get-ChildItem 命令用來尋找不存在的檔案。

        PS> $ErrorView                         # Verify the value.
        NormalView

        PS> get-childitem nofile.txt           # Find a non-existent file.
        Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
        At line:1 char:14
        + get-childitem  <<<< nofile.txt

此範例會顯示當 $ErrorView 值為 CategoryView 時,相同錯誤出現的方式。

        PS> $ErrorView = "CategoryView"        # Change the value to 
                                                 CategoryView

        PS> get-childitem nofile.txt
        ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException

此範例示範 ErrorView 值只會影響錯誤顯示;它不會變更儲存在 $error 自動變數中的錯誤物件的結構。如需 $error 自動變數的詳細資訊,請參閱 about_automatic_variables。

此命令會採用與錯誤陣列中的最近錯誤 (元素 0) 相關聯的 ErrorRecord 物件,以及格式化清單中錯誤物件的所有屬性。

        PS> $error[0] | format-list -property * -force

        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, CmdletProviderContext context)
                       at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(String path,
                       Boolean recurse, 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

$FormatEnumerationLimit
-----------------------

決定顯示中包含多少個列舉項目。此變數不會影響基礎的物件;只會影響顯示。當 $FormatEnumerationLimit 的值小於列舉項目數時,Windows PowerShell 會加入省略符號 (...) 以表示不顯示的項目。

        Valid values: Integers (Int32)
        Default value: 4

範例

此範例示範如何使用 $FormatEnumerationLimit 變數來改善列舉項目的顯示。

此範例中的命令會產生一個資料表,其中列出以下兩個群組中在電腦上執行的所有服務;一個群組適用於執行中的服務,另一個群組適用於已停止的服務。它會使用 Get-Service 命令來取得所有服務,然後透過管線將結果傳送至 Group-Object Cmdlet,以便依服務狀態將結果分組。

結果產生的顯示是一個資料表,其中列出 Name 資料行中的狀態以及 Group 資料行中具有該狀態的處理程序。(若要變更資料行標籤,請使用雜湊表。如需詳細資訊,請參閱 "get-help format-table -examples" 中的範例)。

每個狀態的 Group 資料行中最多列出 4 個服務。若要增加列出的項目數,請將 $FormatEnumerationLimit 的值增加至 1000。

在結果產生的顯示中,Group 資料行中的清單現在受限於行長度。在範例的最後一個命令中,使用 Format-Table 的 Wrap 參數來顯示每個 Status 群組中的所有處理程序。

        PS> $formatenumerationlimit         # Find the current value
        4
        
        PS> get-service | group-object -property status           
                                            # List all services grouped by
                                              status

        Count Name                      Group
        ----- ----                      -----
           60 Running                   {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...}   
           41 Stopped                   {Alerter, AppMgmt, aspnet_state, ATI Smart...}

                                           # The list is truncated after
                                             4 items.


        PS> $formatenumerationlimit = 1000
                                           # Increase the limit to 1000.
        
        PS> get-service | group-object -property status           
                                           # Repeat the command.

        Count Name     Group
        ----- ----     -----
           60 Running  {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec...
           41 Stopped  {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc...


        PS> get-service | group-object -property status | format-table -wrap
                                           # Add the Wrap parameter.

        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}

$Log*Event
----------

Log*Event 喜好設定變數可決定哪些類型的事件會寫入至事件檢視器中的 Windows PowerShell 事件記錄檔。根據預設,只會記錄引擎和提供者事件,但您可以使用 Log*Event 喜好設定變數來自訂您的記錄檔,例如記錄命令相關事件。

Log*Event 喜好設定變數如下所示:

            $LogCommandHealthEvent: Logs errors and exceptions in command initialization
                and processing. Default = $false (not logged).

            $LogCommandLifecycleEvent: 
                Logs the starting and stopping of commands and command pipelines
                and security exceptions in command discovery. Default = $false (not logged).

            $LogEngineHealthEvent: Logs errors and failures of sessions. Default = $true (logged).

            $LogEngineLifecycleEvent: Logs the opening and closing of sessions. 
                Default = $true (logged).

            $LogProviderHealthEvent: Logs provider errors, such as read and write errors,
                lookup errors, and invocation errors. Default = $true (logged).

            $LogProviderLifecycleEvent: Logs adding and removing of Windows PowerShell providers.
                Default = $true (logged). (For information about Windows PowerShell providers, type:
                "get-help about_provider".

若要啟用 Log*Event,請輸入值為 $true 的變數,例如:

            $LogCommandLifeCycleEvent

            - or -

            $LogCommandLifeCycleEvent = $true

若要停用事件類型,請輸入值為 $false 的變數,例如:

            $LogCommandLifeCycleEvent = $false

您啟用的事件只對目前的 Windows PowerShell 主控台有效。若要將設定套用到所有主控台,請在您的 Windows PowerShell 設定檔中儲存變數設定。

$MaximumAliasCount
------------------

決定 Windows PowerShell 工作階段中允許多少個別名。預設值 (4096) 應足以供大部分使用,但您可加以調整以符合您的需求。

        Valid values: 1024 - 32768 (Int32)
        Default: 4096
      
        To count the aliases on your system, type: 

(get-alias).count

$MaximumDriveCount
------------------

判斷指定的工作階段中允許多少個 Windows PowerShell 磁碟機。這包括 Windows PowerShell 提供者所公開並顯示為磁碟機的檔案系統磁碟機和資料存放區,例如 Alias:和 HKLM:磁碟機。

        Valid values: 1024 - 32768 (Int32)
        Default: 4096
      
        To count the aliases on your system, type: 

(get-psdrive).count

$MaximumErrorCount
------------------

判斷工作階段的錯誤歷程記錄中儲存多少個錯誤。

        Valid values: 256 - 32768 (Int32)
        Default: 256

代表每個保留錯誤的物件會儲存在 $Error 自動變數中。此變數包含錯誤記錄物件的陣列,每個錯誤有一個記錄物件。最近的錯誤是陣列中的第一個物件 ($Error[0])。

若要計算您系統上的錯誤,請使用 $Error 陣列的 Count 屬性。類型:

$Error.count

若要顯示特定錯誤,請使用陣列標記法來顯示錯誤。例如,若要查看最近的錯誤,請輸入:

                $Error[0]

若要顯示最舊的保留錯誤,請輸入:

                $Error[($Error.Count -1]

若要顯示 ErrorRecord 物件的屬性,請輸入:

                $Error[0] | format-list -property * -force

在此命令中,Force 參數會覆寫 ErrorRecord 物件的特殊格式並還原為傳統的格式。

若要從錯誤歷程記錄中刪除所有錯誤,請使用錯誤陣列的 Clear 方法。

               PS> $Error.count
               17
               PS> $Error.clear()
               PS>
               PS> $Error.count
               0

若要尋找錯誤陣列的所有屬性和方法,請使用 Get-Member Cmdlet 搭配其 InputObject 參數。當您使用管道將某個物件的集合傳送給 Get-Member 時,Get-Member 會顯示該集合中物件的屬性和成員。當您使用 Get-Member 的 InputObject 參數時,Get-Member 會顯示集合的屬性和方法。

$MaximumFunctionCount
------------------

判斷指定的工作階段中允許多少個函式。

        Valid values: 1024 - 32768 (Int32)
        Default: 4096

若要查看您工作階段中的函式,請使用 Windows PowerShell Function:磁碟機 (由 Windows PowerShell Function 提供者所公開)。(如需 Function 提供者的詳細資訊,請輸入 "get-help function")。

若要列出目前工作階段中的函式,請輸入:

            get-childitem function:

若要計算目前工作階段中的函式,請輸入:

            (get-childitem function:).count

$MaximumHistoryCount
------------------

判斷目前工作階段的命令歷程記錄中儲存多少個命令。

        Valid values: 1 - 32768 (Int32)
        Default: 4096

若要判斷命令歷程記錄中目前儲存的命令數目,請輸入:

            (get-history).count

若要查看工作階段歷程記錄中儲存的命令,使用 Get-History Cmdlet。如需詳細資訊,請參閱 about_History (https://go.microsoft.com/fwlink/?LinkID=113233)。

注意:在 Windows PowerShell 2.0 中,$MaximumHistoryCount 變數的預設值為 64。

$MaximumVariableCount
------------------

判斷指定的工作階段中允許多少個變數,包括自動變數、喜好設定變數,以及您在命令和指令碼中建立的變數。

        Valid values: 1024 - 32768 (Int32)
        Default: 4096

若要查看您工作階段中的變數,請使用 Get-Variable Cmdlet、Windows PowerShell Variable:磁碟機的功能和 Windows PowerShell Variable 提供者。如需 Variable 提供者的詳細資訊,請輸入 "get-help variable"。

若要尋找系統上目前的變數數目,請輸入:

            (get-variable).count

$OFS
----

輸出欄位分隔符號。指定當陣列轉換成字串時用來分隔陣列元素的字元。

        Valid values: Any string.
        Default: Space

根據預設,$OFS 變數不存在且輸出檔案分隔符號是一個空格,但是您可以新增此變數並將它設定為任何字串。

範例

此範例會顯示當陣列轉換成字串時用來分隔值的空格。在此情況下,整數的陣列會儲存在變數中,然後此變數會轉換為字串。

       PS> $array = 1,2,3                 # Store an array of integers.       

       PS> [string]$array                 # Cast the array to a string.
       1 2 3                              # Spaces separate the elements

若要變更分隔符號請,請指派 $OFS 變數的值即可新增該變數。若要正常運作,此變數必須命名為 $OFS。

       PS> $OFS = "+"                     # Create $OFS and assign a "+"

       PS> [string]$array                 # Repeat the command
       1+2+3                              # Plus signs separate the elements

若要還原預設行為,您可以指派一個空格 ("") 給 $OFS 的值或刪除此變數。此命令會刪除變數,然後驗證分隔字元是否為空格。

       PS> Remove-Variable OFS            # Delete $OFS
       PS>

       PS> [string]$array                 # Repeat the command
       1 2 3                              # Spaces separate the elements
       

$OutputEncoding
---------------

判斷當 Windows PowerShell 傳送文字給其他應用程式時所使用的字元編碼方法。

例如,如果應用程式將 Unicode 字串傳回至 Windows PowerShell,您可能需要將此值變更為 UnicodeEncoding 才能正確傳送字元。

        Valid values: Objects derived from an Encoding class, such as
                      ASCIIEncoding, SBCSCodePageEncoding, UTF7Encoding, 
                      UTF8Encoding, UTF32Encoding, and UnicodeEncoding.

        Default: ASCIIEncoding object (System.Text.ASCIIEncoding)

範例

此範例示範如何讓 Windows 中的 FINDSTR 命令作用於針對使用 Unicode 字元的語言 (例如中文) 進行當地語系化的電腦上的 Windows PowerShell 中。第一個命令會尋找 $OutputEncoding 的值。因為此值是編碼物件,所以只會顯示其 EncodingName 屬性。

          PS> $OutputEncoding.EncodingName  # Find the current value
          US-ASCII

在此範例中,FINDSTR 命令用來搜尋存在於 Test.txt 檔案中的兩個中文字元。當此 FINDSTR 命令在 Windows 命令提示字元 (Cmd.exe) 中執行時,FINDSTR 會在文字檔案中尋找字元。不過,當您在 Windows PowerShell 中執行相同的 FINDSTR 命令時,因為 Windows PowerShell 會將字元以 ASCII 文字 (而不是以 Unicode 文字) 傳送至 FINDSTR,所以會找不到字元。

          PS> findstr <Unicode-characters>  # Use findstr to search.
          PS>                               # None found.

若要讓此命令作用於 Windows PowerShell,請將 $OutputEncoding 的值設為主控台的 OutputEncoding 屬性值,這是以針對 Windows 選取的地區設定為基礎。因為 OutputEncoding 是主控台的靜態屬性,請在命令中使用雙冒號 (::)。

          PS> $OutputEncoding = [console]::outputencoding
          PS>                               # Set the value equal to the
                                              OutputEncoding property of the
                                              console.
          PS> $OutputEncoding.EncodingName               
          OEM United States
                                            # Find the resulting value.

由於這項變更,FINDSTR 命令便找到字元。

          PS> findstr <Unicode-characters>               
          test.txt:         <Unicode-characters>        

# Use findstr to search. It find the
                                          characters in the text file.

$ProgressPreference
-------------------

決定 Windows PowerShell 如何回應指令碼、Cmdlet 或提供者所產生的進度更新,例如 Write-Progress Cmdlet 所產生的進度列。Write-Progress Cmdlet 會建立進度列以描述命令的狀態。

有效值:

Stop:不顯示進度列。相反地,它會顯示錯誤訊息並停止執行。

Inquire:不顯示進度列。提示是否允許繼續進行。如果您回覆 Y 或 A,則會顯示進度列。

Continue (預設值):顯示進度列並繼續執行。

SilentlyContinue:執行命令,但不顯示進度列。

$PSEmailServer
--------------

指定用來傳送電子郵件的預設電子郵件伺服器。傳送電子郵件的 Cmdlet (例如 Send-MailMessage Cmdlet) 會使用此喜好設定變數。

$PSDefaultParameterValues
-------------------------

指定 Cmdlet 和進階函式的預設參數值。$PSDefaultParameterValues 的值是雜湊表,其中機碼是由 Cmdlet 名稱和參數名稱組成 (以冒號 (:) 分隔),而此值是您指定的自訂預設值。

此變數在 Windows PowerShell 3.0 中引進。

如需此喜好設定變數的詳細資訊,請參閱 about_Parameters_Default_Values。

$PSModuleAutoloadingPreference
------------------------------

啟用和停用在工作階段中自動匯入模組。"All" 為預設值。無論此變數的值為何,您都可以使用 Import-Module Cmdlet 來匯入模組。

有效值為:

All 模組會在首次使用時自動匯入。若要匯入模組,請取得 (Get-Command) 或使用模組中的任何命令。

ModuleQualified

只有當使用者在模組中使用命令的模組限定名稱時,才會自動匯入模組。例如,如果使用者輸入 "MyModule\MyCommand",Windows PowerShell 會匯入 MyModule 模組。

None 自動匯入模組已在工作階段中停用。若要匯入模組,請使用 Import-Module Cmdlet。

如需自動匯入模組的詳細資訊,請參閱 about_Modules (https://go.microsoft.com/fwlink/?LinkID=144311)。

$PSSessionApplicationName
---------------------------

針對使用 WS 管理技術的遠端命令指定預設應用程式名稱。

系統預設應用程式名稱是 WSMAN,但您可以使用此喜好設定變數來變更預設值。

應用程式名稱是連線 URI 中的最後一個節點。例如,下列範例 URI 中的應用程式名稱是 WSMAN。

           http://Server01:8080/WSMAN

當遠端命令未指定連線 URI 或應用程式名稱時,則會使用預設應用程式名稱。

WinRM 服務會使用應用程式名稱來選取要用來為連線要求提供服務的接聽程式。此參數的值應該符合遠端電腦上接聽程式之 URLPrefix 屬性的值。

若要覆寫系統預設值與此變數的值,並選取特定工作階段的不同應用程式名稱,請使用 New-PSSession、Enter-PSSession 或 Invoke-Command Cmdlet 的 ConnectionURI 或 ApplicationName 參數。

此喜好設定變數設定在本機電腦上,但它會指定遠端電腦上的接聽程式。如果您指定的應用程式名稱不存在遠端電腦上,則用來建立工作階段的命令會失敗。

$PSSessionConfigurationName
---------------------------

指定用於在目前工作階段中建立之 PSSessions 的預設工作階段設定。

此喜好設定變數設定在本機電腦上,但它會指定位於遠端電腦上的工作階段設定。

$PSSessionConfigurationName 變數的值是完整的資源 URI。

預設值:

         https://schemas.microsoft.com/PowerShell/microsoft.PowerShell 

指出遠端電腦上的 Microsoft.PowerShell 工作階段設定。

如果您僅指定設定名稱,則會在前面加上下列架構 URI:

           https://schemas.microsoft.com/PowerShell/

您可以覆寫預設值並使用 New-pssession、Enter-pssession 或 Invoke-command cmdlet 的 ConfigurationName 參數選取特定的工作階段的不同工作階段設定。

您可以隨時變更這個變數的值。當您這樣做時,請記得您選取的工作階段設定必須存在於遠端電腦上。如果沒有,則用來建立採用工作階段設定之工作階段的命令會失敗。

此喜好設定變數不會決定當遠端使用者建立連接到這台電腦的工作階段時使用的本機工作階段設定。不過,您可以使用本機工作階段設定的權限來決定哪些使用者可以使用它們。

$PSSessionOption
----------------

在遠端工作階段中建立進階使用者選項的預設值。這些選項喜好設定會覆寫工作階段選項的系統預設值。

$PSSessionOption 變數包含 PSSessionOption 物件 (System.Management.Automation.Remoting.PSSessionObject)。此物件的每一個屬性都代表一個工作階段選項。例如,NoCompression 屬性會關閉工作階段期間的資料壓縮。

根據預設,$PSSessionOption 變數包含 PSSessionOption 物件,其具有所有選項的預設值,如下所示。

            MaximumConnectionRedirectionCo For descriptions of these options, see the help topic for the unt : 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 Cmdlet 的說明主題。

若要變更 $PSSessionOption 喜好設定變數的值,請使用 New-PSSessionOption Cmdlet 來建立包含您偏好之選項值的 PSSessionOption 物件。將輸出儲存在稱為 $PSSessionOption 的變數中。

例如,

            $PSSessionOption = New-PSSessionOption -NoCompression

若要在每個 Windows PowerShell 工作階段中使用 $PSSessionOption 喜好設定變數,請將可建立 $PSSessionOption 變數的 New-PSSessionOption 命令加入至您的 Windows PowerShell 設定檔。

您也可以設定特定遠端工作階段的自訂選項。您設定的選項優先於系統預設值何 $PSSessionOption 喜好設定變數的值。

若要設定自訂工作階段選項,請使用 New-PSSessionOption Cmdlet 來建立 PSSessionOption 物件。然後,使用 PSSessionOption 物件做為建立工作階段的 Cmdlet 中的 SessionOption 參數值,例如 New-PSSession、Enter-PSSession 和 Invoke-Command。

如需 New-PSSessionOption Cmdlet 的詳細資訊,請參閱 New-PSSessionOption 的說明主題。如需遠端命令和工作階段的詳細資訊,請參閱 about_Remote 和 about_PSSessions。如需使用設定檔的詳細資訊,請參閱 about_Profiles。

$VerbosePreference
------------------

決定 Windows PowerShell 如何回應指令碼、Cmdlet 或提供者所產生的詳細訊息,例如 Write-Verbose Cmdlet 所產生的訊息。通常,詳細訊息描述為了執行命令而執行的動作。

預設不會顯示詳細訊息,但是變更 $VerbosePreference 的值即可變更此行為。

您也可以使用 Cmdlet 的 Verbose 一般參數來顯示或隱藏特定命令的詳細訊息。如需詳細資訊,請輸入:"get-help about_commonparameters"。

有效值:

Stop:顯示詳細訊息和錯誤訊息,然後停止執行。

Inquire:顯示詳細訊息,然後顯示提示來詢問您是否要繼續。

Continue:顯示詳細訊息,然後繼續執行。

SilentlyContinue (預設值):不顯示詳細訊息。繼續執行。

範例

這些範例會顯示不同 $VerbosePreference 值的效果,以及如何使用 Verbose 一般參數來覆寫此喜好設定值。

此範例會顯示 SilentlyContinue 值 (這是預設值) 的效果。

        PS> $VerbosePreference             # Find the current value.
        SilentlyContinue

        PS> Write-Verbose "Verbose message test."              
        PS>                                # Write a verbose message.
                                           # Message is not displayed.

        PS> Write-Verbose "Verbose message test." -verbose     
        VERBOSE: Verbose message test.
                                   # Use the Verbose parameter.

此範例會顯示 Continue 值的效果。

        PS> $VerbosePreference = "Continue"                    
                                           # Change the value to Continue.
        PS> Write-Verbose "Verbose message test."              
                                           # Write a verbose message.
        VERBOSE: Verbose message test.                         
                                           # Message is displayed.

        PS> Write-Verbose "Verbose message test." -verbose:$false
                                           # Use the Verbose parameter with
                                             a value of $false.
        PS>                                  
                                           # Message is not displayed.

此範例會顯示 Stop 值的效果。

        PS> $VerbosePreference = "Stop"                        
                                           # Change the value to Stop.
        PS> Write-Verbose "Verbose message test."              
                                           # Write a verbose message.
        VERBOSE: Verbose message test.
        Write-Verbose : Command execution stopped because the shell variable "VerbosePreference"
        is set to Stop.
        At line:1 char:14
        + Write-Verbose  <<<< "Verbose message test."

       PS> Write-Verbose "Verbose message test." -verbose:$false
                                          # Use the Verbose parameter with
                                            a value of $false
       PS>                                  
                                          # Message is not displayed.

此範例會顯示 Inquire 值的效果。

       PS> $VerbosePreference = "Inquire"                      
                                         # Change the value to Inquire.
       PS> Write-Verbose "Verbose message test."               
       VERBOSE: Verbose message test.
                                         # Write a verbose message.
       Confirm
       Continue with this operation?
       [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): y
       PS>

       PS> Write-Verbose "Verbose message test." -verbose:$false
                                        # Use the Verbose parameter.
       PS>                              
                                        # Message is not displayed.

$WarningPreference
------------------

決定 Windows PowerShell 如何回應指令碼、Cmdlet 或提供者所產生的警告訊息,例如 Write-Warning Cmdlet 所產生的訊息。

預設會顯示警告訊息並繼續執行,但變更 $WarningPreference 的值即可變更此行為。

您也可以使用 Cmdlet 的 WarningAction 一般參數來判斷 Windows PowerShell 如何回應來自特定命令的警告。如需詳細資訊,請輸入:"get-help about_commonparameters"。

有效值:

Stop:顯示警告訊息和錯誤訊息並接著停止執行。

Inquire:顯示警告訊息並接著提示是否允許繼續。

Continue (預設值):顯示警告訊息並接著繼續執行。

SilentlyContinue:不顯示警告訊息。繼續執行。

範例

這些範例會顯示不同 $WarningPreference 值的效果,以及如何使用 WarningAction 一般參數來覆寫此喜好設定值。

此範例會顯示 Continue 值 (這是預設值) 的效果。

            PS> $WarningPreference    # Find the current value.                           
            Continue                  

                                      # Write a warning message.
            PS> Write-Warning "This action can delete data."     
            WARNING: This action can delete data.
                                      
                                      # Use the WarningAction parameter to 
                                      # suppress the warning for this command                                             
            PS> Write-Warning "This action can delete data." -warningaction silentlycontinue     

此範例會顯示 SilentlyContinue 值的效果。

            PS> $WarningPreference = "SilentlyContinue"           
                                      # Change the value to SilentlyContinue.
 
            PS> Write-Warning "This action can delete data."      
            PS>                        # Write a warning message.

       
            PS> Write-Warning "This action can delete data." -warningaction stop     
                                      # Use the WarningAction parameter to stop
                                      # processing when this command generates a
                                      # warning.         
            WARNING: This action can delete data.
            Write-Warning : Command execution stopped because the shell variable
            "WarningPreference" is set to Stop.
            At line:1 char:14
            + Write-Warning <<<<  "This action can delete data." -warningaction stop
                                 

此範例會顯示 Inquire 值的效果。

           PS> $WarningPreference = "Inquire"                    
                                      # Change the value to Inquire.
           PS> Write-Warning "This action can delete data."   
                                      # Write a warning message.     
           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"): y
           PS>

           PS> Write-Warning "This action can delete data." -warningaction silentlycontinue
           PS>                         # Use the WarningAction parameter to change the
                                       # response to a warning for the current command.

此範例會顯示 Stop 值的效果。

           PS> $WarningPreference = "Stop"                       
                                     # Change the value to Stop.

           PS> Write-Warning "This action can delete data."      
                                     # Write a warning message.
           WARNING: This action can delete data.
           Write-Warning : Command execution stopped because the shell variable 
             "WarningPreference" is set to Stop.
           At line:1 char:14
           + Write-Warning  <<<< "This action can delete data."


           PS> Write-Warning "This action can delete data." -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"):                        
                                       # Use the WarningAction parameter to change the
                                       # response to a warning for the current command.

$WhatIfPreference
------------------

決定是否針對支援 WhatIf 的每一個命令自動啟用 WhatIf。啟用 WhatIf 後,Cmdlet 會報告命令的預期效果,但不會執行命令。

有效值:

0 (預設值):不會自動啟用 WhatIf。若要手動啟用,請使用命令的 WhatIf 參數。

1: 所有支援 WhatIf 的命令都會自動啟用 WhatIf。使用者可以使用值為 False 的 WhatIf 命令將它手動停用 (WhatIf:$false)。

詳細說明

當 Cmdlet 支援 WhatIf 時,此 Cmdlet 會報告命令的預期笑過,但不會執行此命令。例如,Windows PowerShell 不會以刪除 test.txt 檔案來回應 Remove-Item 命令,反而會報告將會刪除的項目。後續的 Get-Childitem 命令會確認此檔案未刪除。

              PS> remove-item test.txt
              What if: Performing operation "Remove-Item" on Target "Item: 
                C:\test.txt
              PS> get-childitem test.txt

              Directory: Microsoft.PowerShell.Core\FileSystem::C:


              Mode                LastWriteTime     Length     Name
              ----                -------------     ------     ----
              -a---         7/29/2006   7:15 PM         84     test.txt

範例

這些範例顯示不同 $WhatIfPreference 值的效果。它們也會顯示如何使用 WhatIf Cmdlet 參數來覆寫特定命令的喜好設定值。

此範例會顯示 0 (未啟用) 值 (這是預設值) 的效果。

             PS> $whatifpreference                     
             0                         # Check the current value.

             PS> get-childitem test.txt | format-list FullName
             FullName : C:\test.txt
                                       # Verify that the file exists.

             PS> remove-item test.txt                  
             PS>                       # Delete the file.

             PS> get-childitem test.txt | format-list -property FullName
                                       # Verify that the file is deleted.

             Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist.
             At line:1 char:14
             + get-childitem  <<<< test.txt | format-list fullname

此範例會顯示當 $WhatIfPreference 的值為 0 時使用 WhatIf 參數的效果。

             PS> get-childitem test2.txt | format-list -property FullName 
             FullName : C:\test2.txt
                                      # Verify that the file exists.

             PS> remove-item test2.txt -whatif         
             What if: Performing operation "Remove File" on Target "C:\test2.txt".
                                      # Use the WhatIf parameter

             PS> get-childitem test2.txt | format-list -property FullName
             FullName : C:\test2.txt
                                      # Verify that the file was not deleted

此範例會顯示 1 (啟用 WhatIf) 值的效果。當您使用 Remove-Item 來刪除 Cmdlet 時,Remove-Item 會顯示所要刪除檔案的路徑,但不會刪除該檔案。

             PS> $whatifpreference = 1                 
             PS> $whatifpreference
             1                        # Change the value.
                                      
             PS> remove-item test.txt                  
             What if: Performing operation "Remove File" on Target "C:\test.txt".
                                      # Try to delete a file.

             PS> get-childitem test.txt | format-list FullName
             FullName : C:\test.txt
                                      # Verify that the file exists.

此範例示範當 $WhatIfPreference 的值為 1 時如何刪除檔案。它會使用值為 $false 的 WhatIf 參數。

             PS> remove-item test.txt -whatif:$false
                                      # Use the WhatIf parameter with $false.

此範例示範有一些 Cmdlet 支援 WhatIf 行為,其他 Cmdlet 則不提供支援。在此範例 ($WhatIfPreference 的值是 1 (啟用)) 中,會執行不支援 WhatIf 的 Get-Process 命令,但 Stop-Process 命令會執行 WhatIf 行為。您可以使用值為 $false 的 WhatIf 參數,覆寫 Stop-Process 命令的 WhatIf 行為。

            PS> $whatifpreference = 1                  
                                     # Change the value to 1.
                                                      
            PS> get-process winword  
                                    # A Get-Process command completes.

            Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
            -------  ------    -----      ----- -----   ------     -- -----------
                234       8     6324      15060   154     0.36   2312 WINWORD


           PS> stop-process -name winword              
           What if: Performing operation "Stop-Process" on Target "WINWORD (2312)".
                                    # A Stop-Process command uses WhatIf.

           PS> stop-process -name winword  -whatif:$false
           PS>                      # WhatIf:$false overrides the preference.
           
           PS> get-process winword                     
           Get-Process : Cannot find a process with the name 'winword'. Verify the process name
            and call the cmdlet again.
           At line:1 char:12
           + get-process  <<<< winword
                                    # Verify that the process is stopped.

另請參閱

about_Automatic_Variables

about_CommonParameters

about_Environment_Variables

about_Profiles

about_Remote about_Scopes