共用方式為


關於喜好設定變數

簡短描述

自訂PowerShell行為的變數。

完整描述

PowerShell 包含一組變數,可讓您自定義其行為。 這些喜好設定變數的運作方式就像 GUI 型系統中的選項一樣。

喜好設定變數會影響PowerShell作業環境,而且所有命令都會在環境中執行。 在許多情況下,Cmdlet 具有參數,可用來覆寫特定命令的喜好設定行為。

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

變數 預設值
$ConfirmPreference
$DebugPreference SilentlyContinue
$ErrorActionPreference Continue
$ErrorView NormalView
$FormatEnumerationLimit 4
$InformationPreference SilentlyContinue
$LogCommandHealthEvent False (未記錄)
$LogCommandLifecycleEvent False (未記錄)
$LogEngineHealthEvent True (記錄)
$LogEngineLifecycleEvent True (記錄)
$LogProviderLifecycleEvent True (記錄)
$LogProviderHealthEvent True (記錄)
$MaximumHistoryCount 4096
$OFS (空格字元 (" ") )
$OutputEncoding UTF8Encoding 物件
$ProgressPreference 繼續
$PSDefaultParameterValues (None - 空哈希表)
$PSEmailServer (無)
$PSModuleAutoLoadingPreference 全部
$PSSessionApplicationName wsman
$PSSessionConfigurationName https://schemas.microsoft.com/powershell/Microsoft.PowerShell
$PSSessionOption 請參閱 $PSSessionOption
$Transcript (無)
$VerbosePreference SilentlyContinue
$WarningPreference Continue
$WhatIfPreference False

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

  • env:PSExecutionPolicyPreference
  • $env:PSModulePath

注意

變更喜好設定變數只會在腳本和函式中生效,前提是這些腳本或函式是在與使用喜好設定範圍相同的範圍內定義。 如需詳細資訊,請參閱 about_Scopes

使用喜好設定變數

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

若要顯示特定喜好設定變數的目前值,請輸入變數的名稱。 例如,下列命令會顯示 $ConfirmPreference 變數的值。

 $ConfirmPreference
High

若要變更變數的值,請使用指派語句。 例如,下列語句會將參數的值變更為Medium$ConfirmPreference

$ConfirmPreference = "Medium"

您設定的值是目前 PowerShell 工作階段特有的值。 若要在所有 PowerShell 工作階段中讓變數生效,請將變數新增至您的 PowerShell 配置檔。 如需詳細資訊,請參閱 about_Profiles

從遠端工作

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

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

$ConfirmPreference

判斷 PowerShell 是否在執行 Cmdlet 或函式之前自動提示您進行確認。

變數 $ConfirmPreference 的有效值為 HighMediumLow。 Cmdlet 和函式會指派 的風險。 當變數的值 $ConfirmPreference 小於或等於指派給 Cmdlet 或函式的風險時,PowerShell 會在執行 Cmdlet 或函式之前自動提示您確認。

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

若要變更會話中所有 Cmdlet 和函式的確認行為,請變更 $ConfirmPreference 變數的值。

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

的有效值 $ConfirmPreference

  • :P owerShell 不會自動提示。 若要要求確認特定命令,請使用 Cmdlet 或函式的 Confirm 參數。
  • :P owerShell 會在執行低、中或高風險的 Cmdlet 或函式之前提示確認。
  • :P owerShell 會在執行具有中型或高風險的 Cmdlet 或函式之前,提示確認。
  • :P owerShell 會在執行具有高風險的 Cmdlet 或函式之前提示確認。

詳細說明

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  [?] Help (default is "Y"):

風險的估計值是 Cmdlet 或函式的屬性,稱為 其 ConfirmImpact。 使用者無法變更它。

可能會對系統造成風險的 Cmdlet 和函式具有 Confirm 參數,可用來要求或隱藏單一命令的確認。

由於大部分的 Cmdlet 和函式都會使用預設風險值 ConfirmImpact,且的預設值$ConfirmPreferenceHigh,因此很少會發生自動確認。 不過,您可以將 的值 $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
[?] Help (default is "Y"):

下列範例顯示將的值 $ConfirmPreference 變更為 Medium的效果。 由於大部分的 Cmdlet 和函式都是中度風險,因此會自動確認它們。 若要隱藏單一命令的確認提示,請使用 Confirm 參數搭配 值 $false

$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
[?] 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

此範例顯示 具有 Continue 值的效果$DebugPreference。 偵錯訊息隨即顯示,而且命令會繼續處理。

$DebugPreference = "Continue"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World

此範例使用 Debug 參數搭配值 $false 來隱藏單一命令的訊息。 不會顯示偵錯訊息。

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"

此範例使用 Debug 參數搭配值 $false 來隱藏單一命令的訊息。 不會顯示偵錯訊息,也不會停止處理。

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  [?] Help (default is "Y"):

此範例使用 Debug 參數搭配值 $false 來隱藏單一命令的訊息。 偵錯訊息不會顯示,而且會繼續處理。

Write-Debug -Message "Hello, World" -Debug:$false

$ErrorActionPreference

決定 PowerShell 如何回應非終止錯誤,這是不會停止 Cmdlet 處理的錯誤。 例如,在命令行或腳本、Cmdlet 或提供者中,例如 Cmdlet 所產生的 Write-Error 錯誤。

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

有效值如下:

  • 繼續: (預設) 顯示錯誤訊息並繼續執行。
  • 忽略:隱藏錯誤訊息並繼續執行命令。 Ignore 值適用於每個命令的使用,不適用於儲存的喜好設定。 Ignore 不是變數的有效值 $ErrorActionPreference
  • 查詢:顯示錯誤訊息,並詢問您是否要繼續。
  • SilentlyContinue:沒有效果。 不會顯示錯誤訊息,且不會中斷繼續執行。
  • 停止:顯示錯誤訊息並停止執行。 除了產生的錯誤之外, Stop 值還會對錯誤數據流產生 ActionPreferenceStopException 物件。 資料流
  • 暫停:自動暫停工作流程工作,以允許進一步調查。 調查之後,可以繼續工作流程。 Suspend 值適用於每個命令的使用,不適用於儲存的喜好設定。 Suspend 不是變數的有效值 $ErrorActionPreference

$ErrorActionPreferenceErrorAction 參數不會影響 PowerShell 如何回應停止 Cmdlet 處理的終止錯誤。 如需 ErrorAction 一般參數的詳細資訊,請參閱 about_CommonParameters

範例

這些範例顯示變數不同值 $ErrorActionPreference 的效果。 ErrorAction 參數用來覆寫$ErrorActionPreference值。

此範例顯示 $ErrorActionPreference 預設值 Continue。 產生非終止錯誤。 訊息隨即顯示,並繼續處理。

# Change the ErrorActionPreference to 'Continue'
$ErrorActionPreference = 'Continue'
# Generate a non-terminating error and continue processing the script.
Write-Error -Message  'Test Error' ; Write-Host 'Hello World'
Write-Error -Message  'Test Error' ; Write-Host 'Hello World' : Test Error
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

Hello World

此範例顯示 $ErrorActionPreference 預設值 [查詢]。 產生錯誤,並顯示動作提示。

# Change the ErrorActionPreference to 'Inquire'
$ErrorActionPreference = 'Inquire'
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
Confirm
Test Error
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

此範例顯示設定為 $ErrorActionPreferenceSilentlyContinue。 隱藏錯誤訊息。

# Change the ErrorActionPreference to 'SilentlyContinue'
$ErrorActionPreference = 'SilentlyContinue'
# Generate an error message
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
# Error message is suppressed and script continues processing
Hello World

這個範例會顯示 $ErrorActionPreference 設為 Stop 的 。 它也會顯示產生給 $Error 變數的額外物件。

# Change the ErrorActionPreference to 'Stop'
$ErrorActionPreference = 'Stop'
# Error message is is generated and script stops processing
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'

# Show the ActionPreferenceStopException and the error generated
$Error[0]
$Error[1]
Write-Error -Message 'Test Error' ; Write-Host 'Hello World' : Test Error
At line:1 char:1
+ Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

The running command stopped because the preference variable "ErrorActionPreference"
or common parameter is set to Stop: Test Error

Write-Error -Message 'Test Error' ; Write-Host 'Hello World' : Test Error
At line:1 char:1
+ Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

$ErrorView

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

有效值如下:

  • NormalView: (預設) 針對大部分使用者設計的詳細檢視。 包含錯誤的描述,以及與錯誤相關的物件名稱。

  • CategoryView:專為生產環境設計的簡潔結構化檢視。 其格式如下所示:

    {Category}: ({TargetName}:{TargetType}) :[{Activity}], {Reason}

如需 CategoryView 中欄位的詳細資訊,請參閱 ErrorCategoryInfo 類別。

範例

此範例顯示 當 的值為 $ErrorViewdefault,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,以依服務狀態將結果分組。

結果是數據表,其中列出 [ 名稱 ] 資料行中的狀態,以及 [群組 ] 數據行中的進程。 若要變更數據行標籤,請使用哈希表,請參閱 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-ServiceGroup-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...

搭配 Format-TableWrap 參數使用 以顯示服務清單。

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 參數,其值會覆寫變數的值 $InformationPreferenceWrite-Information 已在 PowerShell 5.0 中引進。

有效值如下:

  • 停止:在發生 Write-Information 命令時停止命令或腳本。
  • 查詢:顯示您在命令中指定的 Write-Information 參考訊息,然後詢問您是否要繼續。
  • 繼續:顯示參考訊息,並繼續執行。
  • 暫止 僅適用於 PowerShell 6 和更新版本中不支援的工作流程。
  • SilentlyContinue: ([預設]) [無效果]。 不會顯示參考訊息,而且腳本會繼續而不會中斷。

$Log*事件

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

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

  • $LogCommandHealthEvent:記錄命令初始化和處理中的錯誤和例外狀況。 預設值為 $false (未記錄) 。
  • $LogCommandLifecycleEvent:記錄命令探索中的命令和命令管線和安全性例外狀況的啟動和停止。 預設值為 $false (未記錄) 。
  • $LogEngineHealthEvent:記錄工作階段的錯誤和失敗。 預設值為 $true (記錄) 。
  • $LogEngineLifecycleEvent:記錄會話的開啟和關閉。 預設值為 $true (記錄) 。
  • $LogProviderHealthEvent:記錄提供者錯誤,例如讀取和寫入錯誤、查閱錯誤和調用錯誤。 預設值為 $true (記錄) 。
  • $LogProviderLifecycleEvent:新增和移除PowerShell提供者的記錄。 預設值為 $true (記錄) 。 如需 PowerShell 提供者的相關信息,請參閱 about_Providers

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

$LogCommandLifeCycleEvent = $true

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

$LogCommandLifeCycleEvent = $false

您啟用的事件僅適用於目前的 PowerShell 控制台。 若要將組態套用至所有控制台,請將變數設定儲存在PowerShell配置檔中。 如需詳細資訊,請參閱 about_Profiles

$MaximumHistoryCount

決定目前會話的命令歷程記錄中儲存多少個命令。

有效值:1 - 32768 () Int32

默認值:4096

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

(Get-History).Count

若要查看儲存在會話歷程記錄中的命令,請使用 Get-History Cmdlet。 如需詳細資訊,請參閱 about_History

$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 類別的物件,例如 ASCIIEncodingSBCSCodePageEncodingUTF7Encoding、UTF8EncodingUTF32EncodingUnicodeEncoding

默認值:UTF8Encoding 物件 (System.Text.UTF8Encoding)

範例

此範例示範如何在使用 Unicode 字元的語言本地化的電腦上,讓 Windows findstr.exe 命令在 PowerShell 中運作,例如中文。

第一個命令會尋找的值 $OutputEncoding。 因為值是編碼物件,所以只會顯示其 EncodingName 屬性。

$OutputEncoding.EncodingName

在此範例中, 會使用findstr.exe 命令來搜尋檔案中 Test.txt 存在的兩個中文字元。 當這個 findstr.exe 命令在 Windows 命令提示字元 (cmd.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 服務進行管理 (WS-Management) 技術。 如需詳細資訊,請參閱 關於 Windows 遠端管理

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

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

http://Server01:8080/WSMAN

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

WinRM 服務會使用應用程式名稱來選取接聽程式來服務連線要求。 參數的值應該符合遠端計算機上接聽程式的 URLPrefix 屬性值。

若要覆寫系統預設值和此變數的值,並選取特定會話的不同應用程式名稱,請使用 New-PSSession、Enter-PSSessionInvoke-Command Cmdlet ConnectionURIApplicationName 參數。

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

$PSSessionConfigurationName

指定用於目前會話中建立 之 PSSession 的預設會話組態。

此喜好設定變數是在本機計算機上設定,但會指定位於遠端電腦上的會話組態。

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

預設值 https://schemas.microsoft.com/PowerShell/microsoft.PowerShell 表示遠端電腦上的 Microsoft.PowerShell 工作階段設定。

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

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

您可以使用 、 Enter-PSSessionInvoke-Command Cmdlet 的 New-PSSessionConfigurationName 參數,覆寫預設值並選取特定會話的不同會話組態。

您可以隨時變更此變數的值。 當您這麼做時,請記住,您選取的會話組態必須存在於遠端電腦上。 如果沒有,用來建立使用會話組態的會話的命令會失敗。

此喜好設定變數不會決定遠端使用者建立連線到這部電腦的會話時,會使用哪些本機會話組態。 不過,您可以使用本機會話設定的許可權來判斷哪些使用者可以使用它們。

$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_Remoteabout_PSSessions

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

$PSSessionOption = New-PSSessionOption -NoCompression

若要在每個 PowerShell 工作階段中使用 $PSSessionOption 喜好設定變數,請將建立 New-PSSessionOption 變數的 $PSSessionOption 命令新增至您的 PowerShell 配置檔。 如需詳細資訊,請參閱 about_Profiles

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

若要設定自定義會話選項,請使用 New-PSSessionOption Cmdlet 來建立 PSSessionOption 物件。 然後,在建立會話的 Cmdlet 中使用 PSSessionOption 物件做為 SessionOption 參數的值,例如 New-PSSessionEnter-PSSessionInvoke-Command

$Transcript

用來 Start-Transcript 指定文字記錄檔的名稱和位置。 如果您未指定 Path 參數的值, Start-Transcript 請使用全域變數值 $Transcript 中的路徑。 如果您尚未建立此變數, Start-Transcript 請將文字記錄儲存在 $Home\My Documents 目錄中做為 \PowerShell_transcript.<time-stamp>.txt 檔案。

$VerbosePreference

決定 PowerShell 如何回應腳本、Cmdlet 或提供者所產生的詳細資訊訊息,例如 Write-Verbose Cmdlet 所產生的訊息。 詳細資訊訊息會描述執行命令所執行的動作。

根據預設,不會顯示詳細資訊訊息,但您可以變更 的值 $VerbosePreference來變更此行為。

您可以使用 Cmdlet 的 Verbose 通用參數來顯示或隱藏特定命令的詳細資訊訊息。 如需詳細資訊,請參閱 about_CommonParameters

有效值如下:

  • 停止:顯示詳細資訊訊息和錯誤訊息,然後停止執行。
  • 查詢:顯示詳細資訊訊息,然後顯示詢問您是否要繼續的提示。
  • 繼續:顯示詳細資訊訊息,然後繼續執行。
  • SilentlyContinue: (預設) 不會顯示詳細資訊訊息。 繼續執行。

範例

這些範例顯示的不同值 $VerbosePreferenceVerbose 參數的效果,以覆寫喜好設定值。

此範例顯示 SilentlyContinue 值的效果,這是預設值。 此命令會使用 Message 參數,但不會將訊息寫入 PowerShell 控制台。

Write-Verbose -Message "Verbose message test."

使用 Verbose 參數時,會寫入訊息。

Write-Verbose -Message "Verbose message test." -Verbose
VERBOSE: Verbose message test.

此範例顯示 Continue 值的效果。 變數 $VerbosePreference 會設定為 [繼續 ],並顯示訊息。

$VerbosePreference = "Continue"
Write-Verbose -Message "Verbose message test."
VERBOSE: Verbose message test.

此範例會使用 Verbose 參數搭配覆寫 Continue 值的值$false。 不會顯示訊息。

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 參數搭配覆寫 Stop 值的值$false。 不會顯示訊息。

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  [?] 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.

此範例使用 WarningAction 參數搭配 SilentlyContinue 值來隱藏警告。 不會顯示訊息。

$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  [?] Help (default is "Y"):

此範例使用 WarningAction 參數搭配 SilentlyContinue 值。 命令會繼續執行,而且不會顯示任何訊息。

$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  [?] Help (default is "Y"):

$WhatIfPreference

判斷是否針對支援它的每個命令自動啟用 WhatIf 。 啟用 WhatIf 時,Cmdlet 會報告命令的預期效果,但不會執行命令。

有效值如下:

  • False (0,未啟用) : (未自動啟用 Default) WhatIf 。 若要手動啟用,請使用 Cmdlet 的 WhatIf 參數。
  • True (1,已啟用) : WhatIf 會在支援它的任何命令上自動啟用。 使用者可以使用 WhatIf 參數搭配 False 值手動停用,例如 -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

本範例顯示 當 值為 $WhatIfPreferenceFalse 時,使用 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

此範例示範當 的 值為 $WhatIfPreferenceTrue 時,如何刪除檔案。 它會使用 WhatIf 參數搭配 值 $false。 使用 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 且支援 WhatIfStop-Process 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 支援 WhatIfWinword 進程不會停止。

Stop-Process -Name Winword
What if: Performing the operation "Stop-Process" on target "WINWORD (15024)".

您可以使用 WhatIf 參數的值$false來覆寫 Stop-ProcessWhatIf 行為。 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

另請參閱

about_Automatic_Variables

about_CommonParameters

about_Environment_Variables

about_Profiles

about_Remote

about_Scopes

about_Variables