惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
博客园_首页
J
Java Code Geeks
Jina AI
Jina AI
B
Blog RSS Feed
量子位
有赞技术团队
有赞技术团队
M
MIT News - Artificial intelligence
L
LangChain Blog
Microsoft Security Blog
Microsoft Security Blog
小众软件
小众软件
博客园 - 聂微东
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog
I
InfoQ
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
Y
Y Combinator Blog
Vercel News
Vercel News
雷峰网
雷峰网

博客园 - 挖土.

学笛子 How to set the compuder to auto login 让 PowerShell 2.0 支持 DotNet FrameWork 4.0 用 Powershell 安装Dotnet FrameWorrk 4.0 PowerShell 调用.netFramework中的静态函数 PowerGUI Visual Studio is now in beta! PowerShell 中定义和使用泛型 PowerShell 如何引用DLL PowerShell中Add-Content 和 Out-File 的区别 给string加几个扩展方法 加快 c++ Builder 5编译速度 Windows 7 下的 SUBST 命令 How to configure the BDE for Windows Vista/7 - 挖土. Linker problems with Borland builder SQL 中的中位值计算 Windows 7的“上帝模式” XML 序列化和反序列化详例代码 给存储过程传递一个表 VSIdeTesthost installation issue - 挖土.
PowerShell: Try...Catch...Finally 实现方法
挖土. · 2012-06-22 · via 博客园 - 挖土.

PowerShell 本身有很多很好的错误控制,但是习惯于.net编程的人员,更喜欢用Try Catch Finally方法,尤其当有一段代码必须被执行到的时候。现在好了,adweigert 想出了一个好方法来实现。这个函数已经在多种情况下测试过,希望能对你有帮助。

 1     function Try
 2     {
 3         param
 4         (
 5             [ScriptBlock]$Command = $(throw "The parameter -Command is required."),
 6             [ScriptBlock]$Catch   = { throw $_ },
 7             [ScriptBlock]$Finally = {}
 8         )
 9        
10         & {
11             $local:ErrorActionPreference = "SilentlyContinue"
12            
13             trap
14             {
15                 trap
16                 {
17                     & {
18                         trap { throw $_ }
19                         &$Finally
20                     }
21                    
22                     throw $_
23                 }
24                
25                 $_ | & { &$Catch }
26             }
27            
28             &$Command
29         }
30 
31         & {
32             trap { throw $_ }
33             &$Finally
34         }
35     }

使用示例:

    

# Example usage 

    Try {
        echo " ::Do some work..."
        echo " ::Try divide by zero: $(0/0)"
    } -Catch {
        echo "  ::Cannot handle the error (will rethrow): $_"
        #throw $_
    } -Finally {
        echo " ::Cleanup resources..."
    }