我正在尝试通过 Azure 自动化循环遍历多个 AzureSQL 数据库的 invoke-sqlcmd。循环中的第一项执行,但其余的都失败了:



我猜我需要在执行下一个之前关闭第一个 invoke-sqlcmd 的连接,但还没有找到使用 invoke-sqlcmd 完成该连接的直接方法。这是我的循环:

param(
# Parameters to Pass to PowerShell Scripts
[parameter(Mandatory=$true)][String] $azureSQLServerName = "myazuresql",
[parameter(Mandatory=$true)][String] $azureSQLCred = "myazureautosqlcred"
        )

# DB Name Array
$dbnamearray = @("database1","database2","database3")
$dbnamearray

# Datatable Name
$tabName = "RunbookTable"

#Create Table object
$table = New-Object system.Data.DataTable "$tabName"

#Define Columns
$col1 = New-Object system.Data.DataColumn dbname,([string])

#Add the Columns
$table.columns.add($col1)

# Add Row and Values for dname Column
ForEach ($db in $dbnamearray)
{
$row = $table.NewRow()
$row.dbname = $db
#Add the row to the table
$table.Rows.Add($row)
}

#Display the table
$table | format-table -AutoSize

# Loop through the datatable using the values per column
$table | ForEach-Object {

# Set loop variables as these are easier to pass then $_.
$azureSQLDatabaseName = $_.dbname

# Execute SQL Query Against Azure SQL
$azureSQLServerName = $azureSQLServerName + ".database.windows.net"
$Cred = Get-AutomationPSCredential -Name $azureSQLCred
$SQLOutput = $(Invoke-Sqlcmd -ServerInstance $azureSQLServerName -Username $Cred.UserName -Password $Cred.GetNetworkCredential().Password -Database $azureSQLDatabaseName -Query "SELECT * FROM INFORMATION_SCHEMA.TABLES " -QueryTimeout 65535 -ConnectionTimeout 60 -Verbose) 4>&1
Write-Output $SQLOutput
}

最佳答案

您可以尝试将每个连接设为 powershell job 。这解决了我前段时间遇到的一个非常相似的问题。 Send-MailMessage closes every 2nd connection when using attachments 如果你想阅读解释。基本上,如果您无法使用 .Close() 方法,您可以通过终止每次运行的整个 session 来强制关闭连接。在理想的世界中,cmdlet 会为您处理所有这些,但并非所有东西都是完美创建的。

# Loop through the datatable using the values per column
$table | ForEach-Object {

# Set loop variables as these are easier to pass then $_.
$azureSQLDatabaseName = $_.dbname

# Execute SQL Query Against Azure SQL
$azureSQLServerName = $azureSQLServerName + ".database.windows.net"
$Cred = Get-AutomationPSCredential -Name $azureSQLCred

# Pass in the needed parameters via -ArgumentList and start the job.
Start-Job -ScriptBlock { Write-Output $(Invoke-Sqlcmd -ServerInstance $args[0] -Username $args[1].UserName -Password $args[1].GetNetworkCredential().Password -Database $args[0] -Query "SELECT * FROM INFORMATION_SCHEMA.TABLES " -QueryTimeout 65535 -ConnectionTimeout 60 -Verbose) 4>&1 } -ArgumentList $azureSQLServerName, $Cred | Wait-Job | Receive-Job

}

这是未经测试的,因为我没有要连接的服务器,但也许通过一些工作,您可以从中有所作为。

关于powershell - Azure SQL 多次调用-SQLCmd 循环和连接错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50299212/

10-13 05:19