about_Preference_Variables
簡短描述
自訂 PowerShell 行為的變數。
完整描述
PowerShell 包含一組變數,可讓您自訂其行為。 這些喜好設定變數的運作方式就像 GUI 型系統中的選項一樣。
喜好設定變數會影響 PowerShell 作業環境,而且所有命令都會在環境中執行。 在許多情況下,Cmdlet 具有參數,可用來覆寫特定命令的喜好設定行為。
下表列出喜好設定變數及其預設值。
變數 | 預設值 |
---|---|
$ConfirmPreference |
High |
$DebugPreference |
SilentlyContinue |
$ErrorActionPreference |
Continue |
$ErrorView |
ConciseView |
$FormatEnumerationLimit |
4 |
$InformationPreference |
SilentlyContinue |
$LogCommandHealthEvent |
$False 未記錄 () |
$LogCommandLifecycleEvent |
$False 未記錄 () |
$LogEngineHealthEvent |
$True 已記錄 () |
$LogEngineLifecycleEvent |
$True 已記錄 () |
$LogProviderLifecycleEvent |
$True 已記錄 () |
$LogProviderHealthEvent |
$True 已記錄 () |
$MaximumHistoryCount |
4096 |
$OFS |
空白字元 (" " ) |
$OutputEncoding |
UTF8Encoding 物件 |
$ProgressPreference |
Continue |
$PSDefaultParameterValues |
@{} (空雜湊表) |
$PSEmailServer |
$Null (無) |
$PSModuleAutoLoadingPreference |
All |
$PSSessionApplicationName |
'wsman' |
$PSSessionConfigurationName |
'http://schemas.microsoft.com/powershell/Microsoft.PowerShell' |
$PSSessionOption |
PSSessionOption 物件 |
$Transcript |
$Null (無) |
$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
會採用其中一個ConfirmImpact
列舉值: 高、 中、 低或 無。
Cmdlet 和函式會指派 高、 中或 低的風險。 當變數的值 $ConfirmPreference
小於或等於指派給 Cmdlet 或函式的風險時,PowerShell 會在執行 Cmdlet 或函式之前自動提示您確認。
如果變數的值 $ConfirmPreference
是 None,PowerShell 永遠不會在執行 Cmdlet 或函式之前自動提示您。
若要變更會話中所有 Cmdlet 和函式的確認行為,請變更 $ConfirmPreference
變數的值。
若要覆寫 $ConfirmPreference
單一命令的 ,請使用 Cmdlet 或函式的 Confirm 參數。 若要要求確認,請使用 -Confirm
。 若要隱藏確認,請使用 -Confirm:$false
。
的有效值 $ConfirmPreference
:
- 無:PowerShell 不會自動提示。 若要要求確認特定命令,請使用 Cmdlet 或函式的 Confirm 參數。
- 低:PowerShell 會在執行低、中或高風險的 Cmdlet 或函式之前提示確認。
- 中:PowerShell 會在執行具有中型或高風險的 Cmdlet 或函式之前,提示確認。
- 高:PowerShell 會在執行具有高風險的 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,且的預設值 $ConfirmPreference
為High,因此很少會發生自動確認。 不過,您可以將 的值 $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
命令列上的命令來回應偵錯訊息。
變數 $DebugPreference
會採用其中一個ActionPreference
列舉值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend或 Break。
某些 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
錯誤。
變數 $ErrorActionPreference
會採用其中一個ActionPreference
列舉值: SilentlyContinue、 Stop、 Continue、 查詢、 忽略、 暫止或 中斷。
您可以使用 Cmdlet 的 ErrorAction 通用參數來覆寫特定命令的喜好設定。
有效值如下:
- 中斷 - 發生錯誤或引發例外狀況時,輸入偵錯工具。
- 繼續: (預設) 顯示錯誤訊息並繼續執行。
- 忽略:隱藏錯誤訊息並繼續執行命令。 Ignore值適用于每個命令的使用,不適用於儲存的喜好設定。 Ignore 不是變數的有效值
$ErrorActionPreference
。 - 查詢:顯示錯誤訊息,並詢問您是否要繼續。
- SilentlyContinue:沒有效果。 不會顯示錯誤訊息,且不會中斷繼續執行。
- 停止:顯示錯誤訊息並停止執行。 除了產生的錯誤之外, Stop 值還會對錯誤資料流程產生 ActionPreferenceStopException 物件。 資料流
- 暫停:自動暫停工作流程工作,以允許進一步調查。 調查之後,可以繼續工作流程。 Suspend值適用于每個命令的使用,不適用於儲存的喜好設定。 Suspend 不是變數的有效值
$ErrorActionPreference
。
$ErrorActionPreference
和 ErrorAction 參數不會影響 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: Test Error
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"):
此範例顯示設定為 $ErrorActionPreference
SilentlyContinue。
隱藏錯誤訊息。
# 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: Test Error
ErrorRecord : Test Error
WasThrownFromThrowStatement : False
TargetSite : System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]
Invoke(System.Collections.IEnumerable)
StackTrace : at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
at Microsoft.PowerShell.Executor.ExecuteCommandHelper(Pipeline tempPipeline,
Exception& exceptionThrown, ExecutionOptions options)
Message : The running command stopped because the preference variable "ErrorActionPreference" or
common parameter is set to Stop: Test Error
Data : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException :
HelpLink :
Source : System.Management.Automation
HResult : -2146233087
Write-Error: Test Error
$ErrorView
決定 PowerShell 中錯誤訊息的顯示格式。
變數 $ErrorView
會採用其中 ErrorView
一個列舉值:NormalView、CategoryView或ConciseView。
有效值如下:
ConciseView: (預設) 提供簡潔的錯誤訊息和進階模組產生器的重構檢視。 如果錯誤來自命令列,則為單行錯誤訊息。 否則,您會收到包含錯誤的多行錯誤訊息,以及顯示該行發生位置的錯誤指標。 如果終端機支援虛擬終端機,則會使用 ANSI 色彩代碼來提供色彩輔色。 輔色可以在 變更。
$Host.PrivateData.ErrorAccentColor
使用Get-Error
Cmdlet 取得完整錯誤的完整詳細檢視,包括內部例外狀況。在 PowerShell 7 中新增了 ConciseView。
NormalView:專為大部分使用者設計的詳細檢視。 包含錯誤的描述,以及與錯誤相關的物件名稱。
CategoryView:專為生產環境設計的簡潔結構化檢視。 其格式如下所示:
{Category}: ({TargetName}:{TargetType}) :[{Activity}], {Reason}
如需 CategoryView中欄位的詳細資訊,請參閱 ErrorCategoryInfo 類別。
範例
此範例顯示 當 的值為 $ErrorView
default, ConciseView時,如何顯示錯誤。 Get-ChildItem
用來尋找不存在的目錄。
Get-ChildItem -path 'C:\NoRealDirectory'
Get-ChildItem: Cannot find path 'C:\NoRealDirectory' because it does not exist.
此範例顯示 當 的值為 $ErrorView
default, ConciseView時,如何顯示錯誤。 Script.ps1
執行 ,並從 語句擲回錯誤 Get-Item
。
./Script.ps1
Get-Item: C:\Script.ps1
Line |
11 | Get-Item -Path .\stuff
| ^ Cannot find path 'C:\demo\stuff' because it does not exist.
此範例示範 當 的值 $ErrorView
變更為 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-Service
和 Group-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-Table
Wrap 參數使用 以顯示服務清單。
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 參數,其值會覆寫變數的值 $InformationPreference
。 Write-Information
已在 PowerShell 5.0 中引進。
變數 $InformationPreference
會採用其中一個ActionPreference
列舉值: SilentlyContinue、 Stop、 Continue、 查詢、 忽略、 暫止或 中斷。
有效值如下:
- 停止:在發生
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 類別的物件,例如ASCIIEncoding、UTF7Encoding、UTF8Encoding、UTF32Encoding和UnicodeEncoding。
預設值: 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
會建立顯示命令狀態的進度列。
變數 $ProgressPreference
會採用其中一個ActionPreference
列舉值: SilentlyContinue、 Stop、 Continue、 查詢、 忽略、 暫止或 中斷。
有效值如下:
- 停止:不會顯示進度列。 相反地,它會顯示錯誤訊息並停止執行。
- 查詢:不會顯示進度列。 提示輸入繼續的許可權。 如果您使用 或
A
回復Y
,則會顯示進度列。 - 繼續: (預設) 顯示進度列並繼續執行。
- SilentlyContinue:執行命令,但不會顯示進度列。
$PSDefaultParameterValues
指定 Cmdlet 和進階函式參數的預設值。
的值 $PSDefaultParameterValues
是雜湊表,其中索引鍵是由 Cmdlet 名稱和參數名稱所組成,並以冒號分隔 (:
) 。 此值是您指定的自訂預設值。
$PSDefaultParameterValues
已在 PowerShell 3.0 中引進。
如需此喜好設定變數的詳細資訊,請參閱 about_Parameters_Default_Values。
$PSEmailServer
指定用來傳送電子郵件訊息的預設電子郵件伺服器。 傳送電子郵件的 Cmdlet 會使用此喜好設定變數,例如 Send-MailMessage Cmdlet。
$PSModuleAutoloadingPreference
啟用和停用會話中模組的自動匯入。 全部 都是預設值。 若要匯入模組,請取得或使用模組中的任何命令。 例如,使用 Get-Command
。 變數 $PSModuleAutoloadingPreference
預設不存在。 未定義變數時的預設行為與 相同 $PSModuleAutoloadingPreference = 'All'
。
不論變數的值為何,您都可以使用 Import-Module 匯入模組。
變數 $PSModuleAutoloadingPreference
會採用其中一個PSModuleAutoLoadingPreference
列舉值: None、 ModuleQualified或 All。
有效值為:
- 全部:模組會在初次使用時自動匯入。
- 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-PSSession或Invoke-Command Cmdlet 的ConnectionURI或ApplicationName參數。
喜好 $PSSessionApplicationName
設定變數是在本機電腦上設定,但它會在遠端電腦上指定接聽程式。 如果您指定的應用程式名稱不存在於遠端電腦上,則建立會話的命令會失敗。
$PSSessionConfigurationName
指定用於目前會話中建立 之 PSSession 的預設會話組態。
這個喜好設定變數是在本機電腦上設定,但它會指定位於遠端電腦上的會話組態。
變數的值 $PSSessionConfigurationName
是完整的資源 URI。
預設值 http://schemas.microsoft.com/PowerShell/microsoft.PowerShell
表示遠端電腦上的 Microsoft.PowerShell 會話組態。
如果您只指定組態名稱,則會在前面加上下列架構 URI:
http://schemas.microsoft.com/PowerShell/
您可以使用 、 Enter-PSSession
或 Invoke-Command
Cmdlet 的 New-PSSession
ConfigurationName參數,覆寫預設值並選取特定會話的不同會話組態。
您可以隨時變更此變數的值。 當您這麼做時,請記住,您選取的會話組態必須存在於遠端電腦上。 如果沒有,用來建立使用會話組態的會話的命令會失敗。
當遠端使用者建立連線到這部電腦的會話時,此喜好設定變數不會決定使用哪個本機會話組態。 不過,您可以使用本機會話設定的許可權來判斷哪些使用者可以使用它們。
$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_Remote 和 about_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-PSSession
、 Enter-PSSession
和 Invoke-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
來變更此行為。
變數 $VerbosePreference
會採用其中一個ActionPreference
列舉值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend或 Break。
有效值如下:
- 停止:顯示詳細資訊訊息和錯誤訊息,然後停止執行。
- 查詢:顯示詳細資訊訊息,然後顯示詢問您是否要繼續的提示。
- 繼續:顯示詳細資訊訊息,然後繼續執行。
- SilentlyContinue: (預設) 不會顯示詳細資訊訊息。 繼續執行。
您可以使用 Cmdlet 的 Verbose 通用參數來顯示或隱藏特定命令的詳細資訊訊息。 如需詳細資訊,請參閱 about_CommonParameters。
範例
這些範例顯示 的不同值 $VerbosePreference
和 Verbose 參數的效果,以覆寫喜好設定值。
這個範例顯示 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
會設定為 [停止 ],並顯示訊息。 命令已停止。
$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
來變更此行為。
變數 $WarningPreference
會採用其中一個ActionPreference
列舉值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend或 Break。
有效值如下:
- 停止:顯示警告訊息和錯誤訊息,然後停止執行。
- 查詢:顯示警告訊息,然後提示繼續許可權。
- 繼續: (預設) 顯示警告訊息,然後繼續執行。
- SilentlyContinue:不會顯示警告訊息。 繼續執行。
您可以使用 Cmdlet 的 WarningAction 一般參數來判斷 PowerShell 如何回應來自特定命令的警告。 如需詳細資訊,請參閱 about_CommonParameters。
範例
這些範例顯示 不同值 $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
本範例顯示 當 值為 $WhatIfPreference
False時,使用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
此範例示範當 的 值為 $WhatIfPreference
True時,如何刪除檔案。 它會使用 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且支援WhatIf的 Stop-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
支援 WhatIf。 Winword進程不會停止。
Stop-Process -Name Winword
What if: Performing the operation "Stop-Process" on target "WINWORD (15024)".
您可以使用WhatIf參數的值 $false
來覆寫 Stop-Process
WhatIf行為。 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