[英]Global Try Catch block in PowerShell 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.