【问题标题】:Unable to catch the exception in try/catch statement in powershell无法在 powershell 的 try/catch 语句中捕获异常
【发布时间】:2019-12-17 20:35:46
【问题描述】:

我试图在 if 语句中捕获异常 - 但 catch 即使条件失败也不会抛出任何异常

我有以下情况,我试图检查文件大小是否为-gt 而不是给定的N 数字。如果条件有效,则try 部分正在执行,但即使条件错误,catch 部分也不会抛出任何错误

$source_dir="C:\test_files_arch"
$Existing_count_of_files=Get-ChildItem $source_dir | Measure-Object | Select-Object Count
$existing_files= ls $source_dir
$Expected_count_of_file=5

#Assuming the Existing_count_of_files is 4, so it should failed

try {
    if($count_of_files.Count -gt $Expected_count_of_file) {
        $existing_files
    }
}
catch {
    Write-Error "Number of file is less"
}

我需要获取所有失败案例的预期 catch 语句。我尝试了很多方法来获取捕获异常,但没有任何效果。

感谢任何人可以提供帮助。

【问题讨论】:

  • TRY/CATCH/FINALLY 东西需要 - 需要 - 一个终止错误。你根本没有任何东西会在你的代码的任何部分触发这样的错误——它必须在try部分。 [咧嘴]
  • 谢谢@Lee_Dailey。在我包含 finally 语句后,它就起作用了
  • 不客气 [grin] ...但是您没有正确使用 try/catch/finally,尽管如此。 [皱眉] 你没有发现任何错误。您只是添加了运行try 然后运行finally 块并且根本没有错误处理的无意义代码。就目前而言,您有一个非常奇怪的脚本块。我会完全删除无意义的代码或重写它以实际进行错误处理。

标签: powershell exception error-handling


【解决方案1】:

正如 Lee_Dailey 在 cmets 中提到的,catch 块仅在它“捕获”从前面的 try 内部抛出的异常(或者,在 PowerShell 中,终止错误)时才会执行块。

返回 $false 的比较语句不是异常 - -gt 应该返回布尔答案!

在您的情况下,只需将 else 块添加到 if 语句即可,try/catch 并没有多大意义:

# I changed the operator to `-ge` - aka. >= or "Greater-than-or-Equal-to"
# based on the assumption that `$Expected_count_of_file` is the minimum number expected 
if($count_of_files.Count -ge $Expected_count_of_file) {
    $existing_files
}
else {
    # This only executes if the `if` condition evaluated to `$false`
    Write-Error "Number of file is less"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多