PowerShell
PowerShell copied to clipboard
Invoke-SqlCmd2 error handling fails to halt on error when EAP is set to SilentlyContinue
Hi,
First of all, thank you for the code - even now, it still provides much value. And I think it's worth a PR.
I run Invoke-SqlCmd2 with a combination of ErrorAction SilentlyContinue
and ErrorVariable
; this gives me a way to parse errors and add value for my use case (I have a wrapper function that injects creds and default values). I do not want to emit the errors to the stream, as they include permission errors where I want my wrapper to retry with the next credential.
I have found that the script attempts to continue execution when continuing makes no sense.
I have a device where https://github.com/RamblingCookieMonster/PowerShell/blob/7d136b1587d166545d5926c0e6fb6678ecc0a1a7/Invoke-Sqlcmd2.ps1#L478 errors with VIEW DATABASE STATE permission denied in database 'master'.
- This obscures the error: https://github.com/RamblingCookieMonster/PowerShell/blob/7d136b1587d166545d5926c0e6fb6678ecc0a1a7/Invoke-Sqlcmd2.ps1#L486 - it should not be inspecting PSBoundParameters to determine whether or not to Write-Verbose; it should Write-Verbose and allow the engine to handle the stream. There is a naked Write-Verbose just above; L486 should also behave like that.
- This also defeats Powershell: https://github.com/RamblingCookieMonster/PowerShell/blob/7d136b1587d166545d5926c0e6fb6678ecc0a1a7/Invoke-Sqlcmd2.ps1#L488-L494 - that is a bad approach for the same reasons. Write-Error respects -EA and EAP; the script should rely on that engine mechanism.
- If L478 throws, then - as far as I can see - there is no scenario in which the script should continue. What is happening is the script moves on to https://github.com/RamblingCookieMonster/PowerShell/blob/7d136b1587d166545d5926c0e6fb6678ecc0a1a7/Invoke-Sqlcmd2.ps1#L526 where it thorws - hard, this time - with
You cannot call a method on a null-valued expression.
Expected behaviour when run with -EA SilentlyContinue and -EV set:
- EV is populated with error representing
VIEW DATABASE STATE permission denied in database 'master'.
- Script returns control to caller after completing the
finally
block at https://github.com/RamblingCookieMonster/PowerShell/blob/7d136b1587d166545d5926c0e6fb6678ecc0a1a7/Invoke-Sqlcmd2.ps1#L512-L519