PowerShell尝试/捕获/最终 [英] PowerShell try/catch/finally

查看:84
本文介绍了PowerShell尝试/捕获/最终的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近编写了一个运行良好的PowerShell脚本-但是,我现在想升级该脚本并添加一些错误检查/处理-但是我似乎很困惑.为什么以下代码不起作用?

I recently wrote a PowerShell script that works great - however, I'd like to now upgrade the script and add some error checking / handling - but I've been stumped at the first hurdle it seems. Why won't the following code work?

try {
  Remove-Item "C:\somenonexistentfolder\file.txt" -ErrorAction Stop
}

catch [System.Management.Automation.ItemNotFoundException] {
  "item not found"
}

catch {
  "any other undefined errors"
  $error[0]
}

finally {
  "Finished"
}

该错误已捕获在第二个catch块中-您可以看到$error[0]的输出.显然,我想在第一块中抓住它.我想念什么?

The error is caught in the second catch block - you can see the output from $error[0]. Obviously I would like to catch it in the first block. What am I missing?

推荐答案

-ErrorAction Stop正在为您带来改变.尝试添加它,看看会得到什么:

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

这篇关于PowerShell尝试/捕获/最终的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆