sql-server - 使用 PowerShell 对 Azure SQL 数据库运行 SQL 查询

标签 sql-server azure powershell

我的任务是从我们的 Azure SQL 数据库检索用户列表。我们有数百个 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   
}

异常(exception):

Exception type: ManagedBatchParser.ParserException
Exception message:
Error: ManagedBatchParser.ParserException

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

最佳答案

以下内容对我有用,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'

或者获取托管身份访问 token ( source )

$resource = "https://database.windows.net"
$endpoint = $env:IDENTITY_ENDPOINT
$header = $env:IDENTITY_HEADER
$apiVersion = "2019-08-01"

$headers = @{ 'X-Identity-Header' = $header }

$url = "$($endpoint)?api-version=$apiVersion&resource=$resource"

$response = Invoke-RestMethod -Method Get -Uri $url -Headers $headers
$response.access_token

关于sql-server - 使用 PowerShell 对 Azure SQL 数据库运行 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58443118/

相关文章:

sql-server - 难以显示组织结构图的 T-SQL(层次结构/递归)

sql - 如何根据另一个sp的多次输出执行一个sp多次

azure - 无法设置部署: Repository UpdateSiteSourceControl operation failed with Microsoft. Web.Hosting.SourceControls

windows - 用于安装字体系列的 Powershell 脚本

执行 20 万行 SQL 查询需要一个多小时

sql - SQL 中 Case 列的乘法

多个特定主机的 Azure Blob CORS 设置

git - Azure 网站部署速度非常慢

powershell - 从txt追加到工作表-Powershell

powershell - XPath SelectNodes的高级条件