test-path returns permission denied - how to do error handling
Somewhat confusingly Test-Path
actually generates an error in a number of cases. Set the standard ErrorAction parameter to SilentlyContinue to ignore it.
if ((Test-Path $Db -ErrorAction SilentlyContinue) -eq $false) {
I cannot answer directly. So this has to do:
I strongly disagree with your answer. Test-Path does show $false when you run it against a network share that is not accessible, but it will be false also (without Exception) when the Server is not reachable.
So your answer simply ignores anything but a reachable share.
What is neccessary however is a try-catch-block that handles this better:
[cmdletbinding()]param( [boolean]$returnException = $true, [boolean]$returnFalse = $false)## Try-Catch Block:try { if ($returnException) { ## Server Exists, but Permission is denied. Test-Path -Path "\\Exists\Data\" -ErrorAction Stop | Out-Null } elseif ($returnFalse) { ## Server does not exist Test-Path -Path "\\NoExists\Data\" -ErrorAction Stop | Out-Null }} catch [UnauthorizedAccessException] { ## Unauthorized write-host "No Access Exception"} catch { ## an error has occurred write-host "Any other Exception here"}
The really important part however is the ErrorAction on the Test-Path command, otherwise the exception will be wrapped around a system management error and is thus not catchable. This is in detail explained here: