dataplat / Invoke-SqlCmd2

PowerShell module containing Invoke-SqlCmd2
MIT License
68 stars 35 forks source link

Connection Timeout Does not work for values less than 15 seconds; Workaround available #35

Open ADMDTO-Jack opened 4 months ago

ADMDTO-Jack commented 4 months ago

Known issue with .net core older versions:

when connecting like so (ignore my own variables, relevant entry is ConnectionTimeout 1: invoke-sqlcmd2 -ServerInstance $serverinstance -Database $database -Query $queryStr -SqlParameters $sqlparams -ConnectionTimeout 1 -ErrorAction Stop

the timeout actually still takes the full 15 seconds

this is related to issue: dotnet sqlclient issue workaround comment

I found it works utilizing the comment's suggestion, by adding the following lines to Invoke-SqlCmd2.ps1 at line 456 (inside of process foreach sqlinstance in serverinstance):

if ($ConnectionTimeout -lt 15 -and $ConnectionTimeout -gt 0) {
    Write-Debug "Setting MultiSubnetFailover to enforce sub-15s connection timeout"
    $CSBuilder["MultiSubnetFailover"] = $true
}

Reproduction: Attempt to invoke-sqlcmd2 with various connection timeout values set, to a sql server which does not exist on the network.

Workaround not necessarily recommended but posted here for reference, as it does appear to have the intended result. Higher timeouts and 0 timeouts not affected by this .net bug

(Note that setting timeout to 1s is not recommended, as it significantly increases failure rate without any particular connection/network issues. But with this change it would be possible.)