【问题标题】:Run SQL query against Azure SQL database using PowerShell使用 PowerShell 对 Azure SQL 数据库运行 SQL 查询
【发布时间】:2022-03-02 06:58:39
【问题描述】:

我的任务是从我们的 Azure SQL 数据库中检索用户列表。我们有 100 多个 Azure SQL 数据库,我想使用 PowerShell 来快速完成任务。

我正在使用连接字符串(Active Directory 集成)。我相信我能够使用 PowerShell 的连接字符串登录到 SQL 数据库。

但是,我在运行 SQL 时遇到错误。下面是代码和异常。你能帮帮我吗?

代码:

try {
    $new = 'Server=tcp:dummy.database.windows.net,1433;Authentication="Active Directory Integrated";Initial Catalog=xtoiteuitbdbsqldb01;Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;'
    $sql = "SELECT * FROM sys.database_principals"
  $temp_result_object = invoke-sqlcmd -ConnectionString $new -Query $sql
} catch {
  "error when running sql $sql"
  write-host "Exception type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception message: $($_.Exception.Message)" -ForegroundColor Red
    write-host "Error: " $_.Exception -ForegroundColor Red   
}

例外:

异常类型:ManagedBatchParser.ParserException
异常消息:
错误:ManagedBatchParser.ParserException

在 ManagedBatchParser.Parser.Parse()
在 Microsoft.SqlServer.Management.PowerShell.ExecutionProcessor.ExecuteTSql(String sqlCommand)

【问题讨论】:

  • 您是否使用来自SQLPS 模块的Invoke-SqlCmd?我不相信它有 -ConnectionString 参数。试试Get-Help Invoke-SqlCmd
  • 我检查了帮助文件,它不包含“-connectionString”。我用什么?
  • 使用单独的-Server-ServerInstance-Database 参数而不是构造单个连接字符串。它只是 sqlcmd.exe 命令行工具的包装,因此基本上可以(大部分)执行该工具可以执行的任何操作。
  • 我正在连接到 Azure sql 数据库(PaaS 产品)。这个想法是使用连接字符串连接到 Azure SQL 数据库,其中 Active Directory 集成提供了我的 Microsoft Azure 以通过提供用户 ID 和密码。
  • 如果您坚持使用 Azure AD 身份验证,那么我认为您不能使用 Invoke-SqlCmd PowerShell cmdlet。您必须直接使用sqlcmd.exe 工具,以便可以使用[-G use Azure Active Directory for authentication] 参数,而Invoke-SqlCmd cmdlet 不会公开该参数。有关示例,请参见 Azure AD token - sqlcmd

标签: sql-server azure powershell


【解决方案1】:

您可以使用 .NET SqlClient 提供程序来使用密码或“Active Directory 集成”身份验证,例如:

# connect to database
$dbConn = New-Object System.Data.SqlClient.SqlConnection
$dbConn.ConnectionString = "Server=tcp:dummy.database.windows.net,1433;Database=DummyDB;Authentication=Active Directory Integrated;Encrypt=True;"
$dbConn.Open()

# construct command
$dbCmd = New-Object System.Data.SqlClient.SqlCommand
$dbCmd.Connection = $dbConn
$dbCmd.CommandText = "SELECT * FROM sys.database_principals"

# fetch all results
$dataset = New-Object System.Data.DataSet
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter
$adapter.SelectCommand = $dbCmd
$adapter.Fill($dataset)

# display results
$dataset.Tables | Format-Table

【讨论】:

  • 我得到了这个异常:使用“0”参数调用“打开”的异常:“发生了一个或多个错误。”在 X $dbConn.Open() + ~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : AggregateException 异常调用“Fill”与“1”参数( s):“发生了一个或多个错误。”在 x + $adapter.Fill($dataset) + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId :聚合异常
  • 嗯,这可能是连接/权限问题,但您需要深入了解该 AggregateException 以查看潜在错误是什么。此答案显示了处理 AggregateExceptions 的示例:stackoverflow.com/a/50804912/8626917
【解决方案2】:

以下对我有用,Connect-AzAccount 通过浏览器触发交互式 AAD 身份验证

Example 11: Connect to Azure SQL Database (or Managed Instance) using an Access Token

Import-Module SQLServer
Import-Module Az.Accounts -MinimumVersion 2.2.0

# Note: the sample assumes that you or your DBA configured the server to accept connections using
#       that Service Principal and has granted it access to the database (in this example at least
#       the SELECT permission).

### Obtain the Access Token: this will bring up the login dialog
Connect-AzAccount
$access_token = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token

# Now that we have the token, we use it to connect to the database 'mydb' on server 'myserver'
Invoke-Sqlcmd -ServerInstance myserver.database.windows.net -Database mydb -AccessToken $access_token`
              -query 'select * from Table1'

【讨论】:

  • 这绝对对我有用。如果可以的话,我会将其标记为答案...
【解决方案3】:

试试下面的方法,看看是否有帮助:

$Svr = "SVR"
$SvrPort = 10003
$Username = "ABC\sql"
$Password = "ABC#@!"

$Password = $Password | ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$Password
$Inst = $Svr + "," + $SvrPort

Get-PSSession

New-PSSession -ComputerName $Svr -Credential $Cred

Invoke-Sqlcmd -ServerInstance $Inst -Database "master" -Query "SELECT @@SERVERNAME AS SERVER_NAME"

Get-PSSession

Get-PSSession | Remove-PSSession

Invoke-Sqlcmd -ServerInstance $Inst -Database "master" -Query "SELECT @@SERVERNAME AS SERVER_NAME"

Get-PSSession

另请参阅以下帖子以供进一步参考:

Active Directory Password Connection Azure SQL Failure from Azure Automation

【讨论】:

  • 我们不想使用用户名和密码。我们想使用 ADO.NET 连接字符串中的“Active Directory 集成”选项。
  • Manjunath - 见上面 golfalot 的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多