运行 写主机输出,而 SqlConnection.Open() 是 运行

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

我想在 运行 宁 SqlConnection.Open().

时有一个尾随的 ..... expands/grows

我不知道该怎么做,当我 运行 命令 SqlConnection.Open() 时输出停止,直到建立连接然后我的代码继续。

我尝试了 while 循环,但是 while 内容在实际连接建立或失败之前什么都不做,这可能需要 10 -15 秒。

$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
}

您有一个单线程脚本。一旦您调用 .Open 方法,在 returns 之前什么都不会发生。我认为多线程是您获得所需内容的唯一方法。 这是 PS 中的多线程示例: multithreading