Search code examples
sql-serverpowershellwhile-loopsqlconnectionparallel.foreach

Run write-host output while SqlConnection.Open() is running


I would like to have a trailing ..... that expands/grows while I'm running SqlConnection.Open().

I can't figure out how to do this and the output stops when i run the command SqlConnection.Open() until the connection is made then my code proceeds.

I tried a while loop, but the while content does nothing until the actual connection is established or fails, which can take 10 -15 seconds.

$waiting = ".", ".", ".", ".", ".";
Try
{
    #write-host -ForegroundColor GREEN "Connecting to SQL Server: $svr"
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $svr ;Database = $db; User ID = $uid ;Password = $pwd;"

    while (!$SqlConnection.State -eq 'Open')
    {
        write-host -ForegroundColor GREEN "Connecting to SQL Server: $svr" -NoNewline
        ForEach ($p in $waiting) {

            Write-Host  -ForegroundColor Cyan "`r$p" -NoNewLine
            Start-Sleep -Milliseconds 300
        }

        $SqlConnection.Open()  
    }

    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.Connection = $Global:SqlConnection
    $SqlCmd.CommandText = $UsrSqlQuery
}

Solution

  • You have a single threaded script. Once you call the .Open method, nothing's going to happen until it returns. I think multithreading is the only way you're going to get what you want. Here's an example of multithreading in PS: multithreading