powershell - PowerShell REPL 中的全局 Try Catch 块
问题描述
我想在 PowerShell 控制台中创建一个全局错误处理程序,它始终可以在没有显式声明的情况下工作。
它的一种(但不仅是)用法是当用户输入某个目录路径(不带Set-Location
)时,它会自动切换到该目录。现在它当然会引发错误。
是否可以实现这样的处理程序?我试图用 ( ) 包装所有内容,try catch
但profile
它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
}
}
推荐阅读
- firebase - 如何在 Firebase 中跟踪应用安装和转化的来源?
- javascript - 如何在firestore中存储二叉树节点
- python - 使用 pip 离线安装包
- javascript - 如何在引导模式中将表格打印为票?
- javascript - 在 React 项目中从 Typescript 迁移
- sql-server - Data Sync between tables from SQL Server & Db2 - how to delete rows
- r - 如果上一个会话意外关闭,RInno 闪亮的应用程序将无法启动
- javascript - 在 AspNet 上隐藏带有 onClick 事件的文本框而不刷新页面
- python - 如何从 DataFrame 中获取元组的行、列列表?
- python - 如何遍历 s3 存储桶以从子文件夹-boto3 的给定日期收集所有密钥