HariUmesh
HariUmesh

Reputation: 81

Unable to catch the exception in try/catch statement in powershell

I am trying to catch the exception in an if statement - but catch not throwing any exception even if the condition is failed

I have below condition where I am trying to check if the size of files is -gt than the given N number. The try part is executing if the condition is valid, but the catch part not throwing any error even if the condition is wrong

$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"
}

I need to get the Expected catch statement for all failure cases. I tried with many ways to get the catch exception, but nothing is working.

Appreciate if any one can help on this.

Upvotes: 0

Views: 541

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

As Lee_Dailey mentioned in the comments, the catch block only ever executes when it "catches" an exception (or, in PowerShell, a terminating error) thrown from inside the preceding try block.

A comparison statement returning $false is not an exception - -gt is supposed to return a boolean answer!

In your case, simply adding an else block to the if statement would do, try/catch doesn't really make much sense:

# 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"
}

Upvotes: 2

Related Questions