共用方式為


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 上、 Standard 非 Windows 上
$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

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

$ConfirmPreference = "Medium"

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

從遠端工作

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

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

$ConfirmPreference

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

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

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 命令行上的命令來回應偵錯訊息。

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

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

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

有效值如下:

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

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

範例

下列範例顯示當命令行輸入命令時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一個列舉值:SilentlyContinueStopContinue查詢IgnoreSuspendBreak

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

有效值如下:

  • 中斷 - 當發生錯誤或引發例外狀況時,請輸入調試程式。
  • 繼續: (預設) 顯示錯誤訊息並繼續執行。
  • 忽略:隱藏錯誤訊息並繼續執行命令。 Ignore 值適用於每個命令的使用,不適用於儲存的喜好設定。 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 預設值 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

此範例顯示設定為 $ErrorActionPreferenceStop。 它也會顯示產生給 $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 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-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...

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

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 中引進。

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

有效值如下:

  • 中斷 - 當您寫入資訊數據流時,請輸入調試程式。
  • 停止:在發生 Write-Information 命令時停止命令或腳本。
  • 查詢:顯示您在命令中指定的 Write-Information 參考訊息,然後詢問您是否要繼續。
  • 繼續:顯示參考訊息,並繼續執行。
  • 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將資料管線傳送至原生應用程式時所使用的字元編碼方法。

注意

在大部分情況下,的值 $OutputEncoding 應該與的值 [Console]::InputEncoding一致。

有效值如下:衍生自 Encoding 類別的物件,例如 ASCIIEncodingUTF7EncodingUTF8Encoding、UTF32EncodingUnicodeEncoding

默認值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()
}

下列範例顯示當管線傳送至上方建立時,字串值 café 如何編碼為 hexdump.ps1 位元組。 它示範字串值是使用 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 所產生的進度列。 Cmdlet Write-Progress 會建立顯示命令狀態的進度列。

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

有效值如下:

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

$PSDefaultParameterValues

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

$PSDefaultParameterValues 已在 PowerShell 3.0 中引進。

如需此喜好設定變數的詳細資訊,請參閱 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 使用 行為。

Standard 模式的行為Windows相同,但模式中的 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 啟用此功能。

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

注意

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 的本機變更。 當 scriptblock 結束時,變數會還原為其先前的值。

$PSSessionApplicationName

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

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

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

http://Server01:8080/WSMAN

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

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

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

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

$PSSessionConfigurationName

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

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

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

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

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

http://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

$PSStyle

從 PowerShell 7.2 開始,您現在可以存取 $PSStyle 自動變數來檢視和變更 ANSI 字串輸出的轉譯。 $PSStylePSStyle 類別的實例。 此類別的成員會定義包含 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

範例

這些範例顯示的不同值 $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 會設定為 [停止 ],並顯示訊息。 命令已停止。

$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 參數會覆寫喜好設定值。

此範例顯示預設值 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

另請參閱