Tuesday, May 16, 2017

invoke-sqlcmd try catch : need switch -ErrorAction


you need the switch  -ErrorAction 'Stop' (of invoke-sqlcmd) to be able to  catch a invoke-sqlcmd error:


    try
    {
        invoke-sqlcmd  -Query $sqlCmd -serverinstance $ServerInstance -ErrorAction 'Stop' # if windows user has not enough rights use other eg.: -Username sa -Password xxx
    }
    catch
    {
        Write-Host "-------------------------------------------------------------" -ForegroundColor Yellow
        Write-Warning "Error in sqlcmd" $sqlCmd
        Write-Warning $_.Exception.Message
    }

No comments: