【发布时间】:2018-10-22 06:39:49
【问题描述】:
我正在尝试通过 Azure 自动化循环调用多个 AzureSQL 数据库的调用 sqlcmd。循环中的第一项执行,但其余的都失败了:
Invoke-Sqlcmd : 发生与网络相关或特定于实例的错误 在建立与 SQL Server 的连接时。服务器没有 找到或无法访问。验证实例名称是否正确 并且 SQL Server 配置为允许远程连接。 (提供者:命名管道提供者,错误:40 - 无法打开 连接到 SQL Server)
我猜我需要在执行下一个之前从第一个 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
}
【问题讨论】:
-
先看看这个链接link。
-
我的第一个 sql 命令调用有效。连接可能仍处于打开状态,因此循环中的第二次和后续尝试失败
-
要控制打开/关闭连接,您应该使用 System.Data.SqlClient 并使用
SqlConnection.Open()和SqlConnection.Close()。 -
如何在它们之间调用invoke-sqlcmd?这是 AzureSQL,所以我的 invoke-sqlcmd 需要服务器和数据库名称,所以 connection.open 似乎是双重连接
标签: powershell azure-sql-database azure-automation invoke-sqlcmd