簡體   English   中英

PowerShell REPL 中的全局 Try Catch 塊

[英]Global Try Catch block in PowerShell REPL

我想在 PowerShell 控制台中創建一個全局錯誤處理程序,該處理程序將始終在沒有顯式聲明的情況下工作。

它的一個(但不僅是)用法是當用戶輸入某個目錄路徑(沒有Set-Location )時,它會自動切換到該目錄。 現在它當然會引發錯誤。

在此處輸入圖片說明

是否可以實現這樣的處理程序? 我嘗試在profile使用try catch包裝所有內容( C:\\Users\\...\\Documents\\PowerShell\\profile.ps1 ),但它在 REPL 中沒有幫助。

對於通用全局錯誤處理程序,您通常會使用trap

不過,在這個特定用例中,我們可以利用CommandNotFoundAction處理程序:

$ExecutionContext.InvokeCommand.CommandNotFoundAction = {
  param([string]$CommandName, [System.Management.Automation.CommandLookupEventArgs]$evtArgs)

  # Test if the "command" in question is actually a directory path
  if(Test-Path $CommandName -PathType Container){
    # Tell PowerShell to execute Set-Location against it instead
    $evtArgs.CommandScriptBlock = {
      Set-Location $CommandName
    }.GetNewClosure()
    # Tell PowerShell that we've provided an alternative, it can stop looking for commands (and stop throwing the error)
    $evtArgs.StopSearch = $true
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM