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.