1

I'm trying to fetch a file using Get-SCPFile from the Posh-SSH module and when such a file doesn't exists, an error is thrown. I want to catch said error and attempt the operation with a different file name.

try {
  Write-Host "Primary attempt with" $target
  # throw "up"
  Get-SCPFile -RemoteFile ($origin + $target + ".csv") ...
}
catch {
  $target = $target -replace "1$", "2"
  Write-Host "Secondary attempt with" $target
  Get-SCPFile -RemoteFile ($origin + $target + ".csv") ...
}
finally {
  Write-Host "Final action performed with" $target
}

For some reason, when the file doesn't exist, I get to finally and the screen shows red error but the catch part is omitted. However, when I activate my throw up, the exception is caught as expected and the statement in catch executes.

Googling along the lines of PS error not caught gave me a very widespread and uninformative results.

I omitted the exact call for brevity reasons since the invokation as such seems to work properly but for the curious reader (and in case I'm missing a relevant detail), here it is.

Get-SCPFile -ComputerName $server 
            -Credential $credential 
            -RemoteFile ($origin + $target + ".csv") 
            -LocalFile ($destination + $target + ".csv")  

Optimally, I'd also like to test the existence of the file prior to actually fetching it. However, the package I'm using only has documentation on Test-SFTP, not Test-SCP. Also, even more importantly in this context, the question of the uncaught exception is the main subject.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • 1
    In short: `try` / `catch` only acts on _terminating_ errors, whereas it is far more typical for cmdlets to report _non-terminating_ errors. For the `catch` block to get invoked, non-terminating errors must be promoted to terminating ones by passing `-ErrorAction Stop` or by setting `$ErrorActionPreference = 'Stop'` beforehand. See the [linked answer](https://stackoverflow.com/a/59641995/45375) for more information. – mklement0 Jan 03 '21 at 18:34
  • Your question - which is much better formulated than the first linked duplicate (I've since added another duplicate that better resembles yours in wording and problem statement) - will continue to remain discoverable, and the duplicate notice at the top is a clear signal to future readers that they need to go elsewhere for the solution. To help them, I've posted my comment with a succinct summary, plus a direct link to the relevant _answer_ (in my estimation). If we were to reopen your question, it would call for the very same answer as the linked one, and for that reason it is a duplicate. – mklement0 Jan 04 '21 at 14:05

0 Answers0