共用方式為


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 (已記錄)
$LogProviderHealthEvent $True (已記錄)
$LogProviderLifecycleEvent $True (已記錄)
$MaximumHistoryCount 4096
$OFS 空白 (" "
$OutputEncoding UTF8Encoding 物件
$ProgressPreference Continue
$PSDefaultParameterValues @{} (空白哈希表)
$PSEmailServer $Null(無)
$PSModuleAutoLoadingPreference All
$PSNativeCommandArgumentPassing Windows 上的 Windows,非 Windows 上的 Standard
$PSNativeCommandUseErrorActionPreference $True
$PSSessionApplicationName 'wsman'
$PSSessionConfigurationName 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell'
$PSSessionOption PSSessionOption 物件
$PSStyle PSStyle 物件
$Transcript $Null(無)
$VerbosePreference SilentlyContinue
$WarningPreference Continue
$WhatIfPreference $False

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

  • env:PSExecutionPolicyPreference
  • $env:PSModulePath

注意

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

使用喜好設定變數

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

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

 $ConfirmPreference
High

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

$ConfirmPreference = "Medium"

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

從遠端工作

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

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

$ConfirmPreference

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

$ConfirmPreference 變數會採用其中一個 ConfirmImpact 列舉值:HighMediumLowNone

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

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

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

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

$ConfirmPreference的有效值:

  • None: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 的值變更為 中度Low來啟用自動確認。

例子

此範例顯示 $ConfirmPreference 變數預設值的效果,HighHigh 值只會確認高風險 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 列舉值:SilentlyContinueStopContinue查詢IgnoreSuspendBreak

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

您可以使用 cmdlet 的 Debug Common 參數來顯示或隱藏特定命令的偵錯訊息。 如需詳細資訊,請參閱 about_CommonParameters

有效值如下所示:

  • 中斷 - 發生錯誤或引發例外狀況時輸入調試程式。
  • 停止:顯示偵錯訊息並停止執行。 將錯誤寫入主控台。
  • 詢問:顯示偵錯訊息,並詢問您是否要繼續。
  • 繼續:顯示偵錯訊息並繼續執行。
  • SilentlyContinue: (預設值) 沒有效果。 偵錯訊息不會顯示,而且不會中斷執行。

Debug 一般參數新增至命令,當命令設定為產生偵錯訊息時,會將 $DebugPreference 變數的值變更為 [繼續]。

例子

下列範例顯示當命令行輸入 Write-Debug 命令時,變更 $DebugPreference 值的效果。 此變更會影響所有偵錯訊息,包括 Cmdlet 和腳本所產生的訊息。 這些範例顯示 Debug 參數,其中會顯示或隱藏與單一命令相關的偵錯訊息。

此範例顯示 $DebugPreference 變數預設值的效果,SilentlyContinue。 根據預設,不會顯示 Write-Debug Cmdlet 的偵錯訊息,而且會繼續處理。 使用 Debug 參數時,它會覆寫單一命令的喜好設定。 偵錯訊息隨即顯示。

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

此範例顯示 $DebugPreferenceContinue 值的效果。 偵錯訊息隨即顯示,命令會繼續處理。

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

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

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

此範例顯示 $DebugPreference 設定為 Stop 值的效果。 偵錯訊息隨即顯示,且命令已停止。

$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 或提供者中,例如 Write-Error Cmdlet 所產生的錯誤。

$ErrorActionPreference 變數會採用其中一個 ActionPreference 列舉值:SilentlyContinueStopContinue查詢IgnoreSuspendBreak

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

有效值如下所示:

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

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

許多原生命令會寫入 stderr 做為其他資訊的替代數據流。 如果 $ErrorActionPreference 設定為將輸出設為靜音狀態,則查看錯誤時,此行為可能會造成混淆,或使用者可能會遺失其他輸出資訊。

從 PowerShell 7.2 開始,從原生命令重新導向的錯誤記錄,例如使用重新導向運算符 (2>&1),不會寫入 $Error 變數,而喜好設定變數 $ErrorActionPreference 不會影響重新導向的輸出。

PowerShell 7.3 新增了實驗性功能,可讓您控制寫入 stderr 訊息的處理方式。

如需詳細資訊,請參閱 $PSNativeCommandUseErrorActionPreference

例子

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

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

# 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

此範例顯示設定為 Stop$ErrorActionPreference。 它也會顯示產生至 $Error 變數的額外物件。

# Change the ErrorActionPreference to 'Stop'
$ErrorActionPreference = 'Stop'
# Error message 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 列舉值:NormalViewCategoryViewConciseView

有效值如下所示:

  • ConciseView:( 預設值) 提供簡潔的錯誤訊息和進階模組產生器的重構檢視。 從 PowerShell 7.2 起,如果錯誤來自命令行或腳本模組,輸出就會是單行錯誤訊息。 否則,您會收到多行錯誤訊息,其中包含錯誤,以及顯示該行發生位置之錯誤的指標。 如果終端機支援虛擬終端機,則會使用 ANSI 色彩代碼來提供色彩輔色。 輔色可以在 $Host.PrivateData.ErrorAccentColor變更。 使用 Get-Error Cmdlet 來完整檢視完整錯誤,包括內部例外狀況。

    PowerShell 7 已新增 ConciseView

  • NormalView:專為大部分用戶設計的詳細檢視。 包含錯誤的描述,以及與錯誤相關的物件名稱。

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

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

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

例子

此範例顯示當 $ErrorView 的值是預設值時,ConciseView時,如何顯示錯誤。 Get-ChildItem 可用來尋找不存在的目錄。

Get-ChildItem -path 'C:\NoRealDirectory'
Get-ChildItem: Cannot find path 'C:\NoRealDirectory' because it does not exist.

此範例顯示當 $ErrorView 的值是預設值時,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

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

$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,依服務狀態將結果分組。

結果是一個數據表,其中列出 [Name] 數據行中的狀態,以及 [群組] 數據行中的進程。 若要變更資料列標籤,請使用哈希表,請參閱 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-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 變數的值。 PowerShell 5.0 中引進 Write-Information

$InformationPreference 變數會採用其中一個 ActionPreference 列舉值:SilentlyContinueStopContinue查詢IgnoreSuspendBreak

有效值如下所示:

  • 中斷 - 當您寫入資訊數據流時,請輸入調試程式。
  • 停止:在發生 Write-Information 命令時停止命令或腳本。
  • 查詢:顯示您在 Write-Information 命令中指定的資訊訊息,然後詢問是否要繼續。
  • 繼續:顯示參考訊息,並繼續執行。
  • SilentlyContinue: (預設值) 沒有效果。 不會顯示參考訊息,而且腳本會繼續而不會中斷。

$Log*事件

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

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

  • $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 將數據輸送到原生應用程式時所使用的字元編碼方法。

注意

在大部分案例中,$OutputEncoding 的值應該與 [Console]::InputEncoding的值一致。

有效值如下:衍生自 Encoding 類別的物件,例如 ASCIIEncodingUTF7EncodingUTF8EncodingUTF32Encoding,以及 UnicodeEncoding

預設UTF8Encoding 物件。

例子

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

$OutputEncoding.EncodingName

其餘範例會使用下列儲存為 hexdump.ps1 的 PowerShell 腳本來說明 $OutputEncoding的行為。

$inputStream = [Console]::OpenStandardInput()
try {
    $buffer = [byte[]]::new(1024)
    $read = $inputStream.Read($buffer, 0, $buffer.Length)
    Format-Hex -InputObject $buffer -Count $read
} finally {
    $inputStream.Dispose()
}

下列範例示範當管線傳送至上面建立的 hexdump.ps1 時,字元串值 café 如何編碼為位元組。 它示範字串值是使用 UTF8Encoding 配置進行編碼。

'café' | pwsh -File ./hexdump.ps1
   Label: Byte[] (System.Byte[]) <28873E25>

          Offset Bytes                                           Ascii
                 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
          ------ ----------------------------------------------- -----
0000000000000000 63 61 66 C3 A9 0D 0A                            caf�

下列範例顯示當將編碼變更為 UnicodeEncoding時,位元組如何變更。

$OutputEncoding = [System.Text.Encoding]::Unicode
'café' | pwsh -File ./hexdump.ps1
   Label: Byte[] (System.Byte[]) <515A7DC3>

          Offset Bytes                                           Ascii
                 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
          ------ ----------------------------------------------- -----
0000000000000000 FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00       ÿþc a f é � �

$ProgressPreference

決定 PowerShell 如何回應腳本、Cmdlet 或提供者所產生的進度更新,例如 Write-Progress Cmdlet 所產生的進度列。 Write-Progress Cmdlet 會建立顯示命令狀態的進度列。

$ProgressPreference 變數會採用其中一個 ActionPreference 列舉值:SilentlyContinueStopContinue查詢IgnoreSuspendBreak

有效值如下所示:

  • 中斷 - 當您寫入進度數據流時,請輸入調試程式。
  • 停止:不會顯示進度列。 相反地,它會顯示錯誤訊息並停止執行。
  • 詢問:不會顯示進度列。 提示輸入許可權以繼續。 如果您使用 YA回復,則會顯示進度列。
  • 繼續:(預設值) 顯示進度列並繼續執行。
  • SilentlyContinue:執行命令,但不會顯示進度列。

$PSDefaultParameterValues

指定 Cmdlet 和進階函式參數的預設值。 $PSDefaultParameterValues 的值是哈希表,其中索引鍵是由以冒號 (:) 分隔的 Cmdlet 名稱和參數名稱所組成。 值是您指定的自訂預設值。

powerShell 3.0 中引進了 $PSDefaultParameterValues

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

$PSEmailServer

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

$PSModuleAutoloadingPreference

啟用和停用會話中模組的自動匯入。 根據預設,$PSModuleAutoloadingPreference 變數不存在。 未定義變數時的預設行為與 $PSModuleAutoloadingPreference = 'All'相同。

若要自動匯入模組,請取得或使用模組中包含的命令。

$PSModuleAutoloadingPreference 變數會採用其中一個 PSModuleAutoLoadingPreference 列舉值:

  • All:模組會在初次使用時自動匯入。
  • ModuleQualified:只有在使用者使用模組中命令的模組限定名稱時,才會自動匯入模組。 例如,如果使用者輸入 MyModule\MyCommand,PowerShell 會匯入 MyModule 模組。
  • None:停用模組的自動匯入。 若要匯入模組,請使用 Import-Module Cmdlet。

如需自動匯入模組的詳細資訊,請參閱 about_Modules

$PSNativeCommandArgumentPassing

PowerShell 7.3 變更了剖析原生命令命令行的方式。 新的 $PSNativeCommandArgumentPassing 喜好設定變數會控制此行為。

謹慎

新行為是先前行為 重大變更。 這可能會中斷在叫用原生應用程式時解決各種問題的腳本和自動化。

自動變數 $PSNativeCommandArgumentPassing 可讓您在運行時間選取行為。 有效值為 LegacyStandardWindowsLegacy 是歷史行為。

默認會定義 $PSNativeCommandArgumentPassing 變數,但值是平臺特定的。

  • 在 Windows 上,喜好設定為 Windows
  • 在非 Windows 平臺上,喜好設定為 Standard
  • 如果您已移除 $PSNativeCommandArgumentPassing 變數,PowerShell 會使用 Standard 行為。

WindowsStandard 模式的行為相同,但在 Windows 模式中,PowerShell 會使用執行下列檔案時傳遞的自變數 Legacy 行為。

  • cmd.exe
  • cscript.exe
  • find.exe
  • sqlcmd.exe
  • wscript.exe
  • 以下列結尾的檔案:
    • .bat
    • .cmd
    • .js
    • .vbs
    • .wsf

如果 $PSNativeCommandArgumentPassing 設定為 LegacyStandard,剖析器不會檢查這些檔案。 如需新行為的範例,請參閱 about_Parsing

PowerShell 7.3 也新增了追蹤原生命令的參數系結的功能。 如需詳細資訊,請參閱 Trace-Command

$PSNativeCommandUseErrorActionPreference

此喜好設定變數可在PowerShell 7.3和更新版本中使用,並啟用 PSNativeCommandErrorActionPreference 功能。

啟用此功能后,具有非零結束代碼的原生命令會在 $PSNativeCommandUseErrorActionPreference$true時,根據 $ErrorActionPreference 發出錯誤。

注意

PSNativeCommandUseErrorActionPreference 是 PowerShell 7.3 中新增的實驗性功能。 如需詳細資訊,請參閱 使用實驗性功能

某些原生命令,例如 robocopy 使用非零結束代碼來表示錯誤以外的資訊。 在這些情況下,您可以暫時停用行為,並防止非零結束代碼發出錯誤。

& {
    # Disable $PSNativeCommandUseErrorActionPreference for this scriptblock
    $PSNativeCommandUseErrorActionPreference = $false
    robocopy.exe D:\reports\operational "\\reporting\ops" CY2022Q4.md
    if ($LASTEXITCODE -gt 8) {
        throw "robocopy failed with exit code $LASTEXITCODE"
    }
}

在此範例中,腳本區塊內會變更 $PSNativeCommandUseErrorActionPreference 變數。 變更是 scriptblock 的本機變更。 當 scriptblock 結束時,變數會還原成其先前的值。

$PSSessionApplicationName

指定使用 Web Services for Management (WS-Management) 技術之遠端命令的預設應用程式名稱。 如需詳細資訊,請參閱 關於 Windows 遠端管理

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

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

http://Server01:8080/WSMAN

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

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

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

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

$PSSessionConfigurationName

指定用來在目前工作階段中建立新工作階段的預設工作階段組態。

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

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

默認值 http://schemas.microsoft.com/PowerShell/microsoft.PowerShell 表示遠端電腦上的 Microsoft.PowerShell 工作話組態。

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

http://schemas.microsoft.com/PowerShell/

您可以使用 New-PSSessionEnter-PSSessionInvoke-Command Cmdlet 的 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_Remoteabout_PSSessions

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

$PSSessionOption = New-PSSessionOption -NoCompression

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

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

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

$PSStyle

從 PowerShell 7.2 開始,您現在可以存取 $PSStyle 自動變數,以檢視和變更 ANSI 字串輸出的轉譯。 是 PSStyle 類別 實例。 這個類別的成員會定義包含 ANSI 逸出序列的字串,以控制終端機中的文字轉譯。

基底成員會傳回對應至其名稱的 ANSI 逸出序列字串。 這些值可設定為允許自定義。 屬性名稱可讓您更輕鬆地使用 Tab 鍵自動完成建立裝飾字串。 例如:

"$($PSStyle.Background.BrightCyan)Power$($PSStyle.Underline)$($PSStyle.Bold)Shell$($PSStyle.Reset)"

BackgroundForeground 成員也有 FromRgb() 方法來指定 24 位色彩。

如需 $PSStyle的詳細資訊,請參閱 about_ANSI_Terminals

$Transcript

Start-Transcript 用來指定文字記錄檔的名稱和位置。 如果您未指定 Path 參數的值,Start-Transcript 會使用 $Transcript 全域變數值中的路徑。 如果您尚未建立此變數,Start-Transcript 使用預設名稱,將文字記錄儲存在下列位置:

  • 在 Windows 上:$HOME\Documents
  • 在 Linux 或 macOS 上:$HOME

預設檔案名為:PowerShell_transcript.<computername>.<random>.<timestamp>.txt

$VerbosePreference

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

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

$VerbosePreference 變數會採用其中一個 ActionPreference 列舉值:SilentlyContinueStopContinue查詢IgnoreSuspendBreak

有效值如下所示:

  • 中斷 - 當您寫入 Verbose 數據流時,請輸入調試程式。
  • 停止:顯示詳細資訊訊息和錯誤訊息,然後停止執行。
  • 詢問:顯示詳細資訊訊息,然後顯示詢問您是否要繼續的提示。
  • 繼續:顯示詳細資訊訊息,然後繼續執行。
  • 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 = "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的值來變更此行為。

$WarningPreference 變數會採用其中一個 ActionPreference 列舉值:SilentlyContinueStopContinue查詢IgnoreSuspendBreak

有效值如下所示:

  • 中斷 - 在寫入警告訊息時輸入調試程式。
  • 停止:顯示警告訊息和錯誤訊息,然後停止執行。
  • 詢問:顯示警告訊息,然後提示許可權繼續。
  • 繼續:(預設值) 顯示警告訊息,然後繼續執行。
  • SilentlyContinue:不會顯示警告訊息。 繼續執行。

您可以使用 cmdlet 的 WarningAction 常見參數來判斷 PowerShell 如何回應特定命令的警告。 如需詳細資訊,請參閱 about_CommonParameters

例子

這些範例顯示不同值 $WarningPreference的效果。 WarningAction 參數會覆寫喜好設定值。

本範例顯示預設值的效果,繼續

$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。 當 WhatIf 啟用時,Cmdlet 會報告命令的預期效果,但不會執行命令。

有效值如下所示:

  • False0,未啟用):[預設值] WhatIf 未自動啟用。 若要手動啟用,請使用 Cmdlet 的 WhatIf 參數。
  • True1已啟用):支援 WhatIf 的任何命令上都會自動啟用。 使用者可以使用 WhatIf 參數,並將值為 False 手動停用,例如 -WhatIf:$false

例子

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

本範例顯示設定為預設值 $WhatIfPreference 變數的效果,False。 使用 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

本範例顯示設定為 值 $WhatIfPreference 變數的效果,True。 當您使用 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時,如何刪除檔案。 它會使用具有 $false值的 WhatIf 參數。 使用 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 Cmdlet 的範例。 $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

支援 whatIfWinword 程式不會停止。

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

您可以使用具有 $false值的 WhatIf 參數,覆寫 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

另請參閱