首页 > 解决方案 > 无法在 powershell 的 try/catch 语句中捕获异常

问题描述

我试图在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 语句。我尝试了很多方法来获取捕获异常,但没有任何效果。

感谢是否有人可以提供帮助。

标签: powershellexceptionerror-handling

解决方案


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

$false返回的比较语句也不例外 --gt应该返回布尔答案!

在您的情况下,只需在语句中添加一个else块就可以了,实际上并没有多大意义:iftry/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"
}

推荐阅读