无法在 PowerShell 中使用 Invoke-Sqlcmd 连接到 Azure SQL 数据库

问题描述 投票:0回答:1

我目前在使用 PowerShell 的 Invoke-Sqlcmd cmdlet 连接到 Azure SQL 数据库时遇到问题。我能够在我的计算机上使用 WSL Ubuntu 中的 sqlcmd(版本 18.2.0001.1 Linux)成功连接到数据库,但是当我尝试从同一台计算机使用 Invoke-Sqlcmd 时,它会失败。 我正在尝试连接在 Azure SQL Server 上设置为 Microsoft Entra 管理员的服务原则。

以下是我如何获取和存储服务主体的访问令牌:

az account get-access-token --resource https://database.windows.net --output tsv | cut -f 1 | tr -d '\n' | iconv -f ascii -t UTF-16LE > TOKEN_LOCATION

这是运行良好的 sqlcmd 命令:

sqlcmd -S myserver.database.windows.net -d mydatabase -G -P TOKEN_LOCATION -C -Q "print 'hello'"

但是,当我尝试使用以下 Invoke-Sqlcmd 命令时,它不起作用:

Invoke-Sqlcmd -ServerInstance myserver.database.windows.net -Database mydatabase -AccessToken (TOKEN_LOCATION or $TOKEN) -query "print 'hello'" -TrustServerCertificate -Verbose

我正在使用 Invoke-Sqlcmd 版本 22.2。当我运行上述命令时,我收到以下错误消息:

Invoke-Sqlcmd: Login failed for user '<token-identified principal>'.
Invoke-Sqlcmd: Incorrect syntax was encountered while parsing ''.

我还尝试创建 System.Data.SqlClient.SqlConnection 来打开连接。像这样:

$SQLConnection = New-Object System.Data.SqlClient.SqlConnection($ConnectionString)
$SQLConnection.AccessToken = $token
$SQLConnection.Open()

收到以下错误:

Exception calling "Open" with "0" argument(s): "A connection was successfully established with the server, but then an error occurred during the login process. (provider: TCP Provider, error
: 0 - An existing connection was forcibly closed by the remote host.)"

任何人都可以帮助我理解为什么 Invoke-Sqlcmd 在这种情况下不起作用以及如何解决此问题?甚至我如何获得更多诊断。

提前谢谢您!

azure powershell azure-sql-database sqlcmd invoke-sqlcmd
1个回答
0
投票
Invoke-Sqlcmd: Login failed for user '<token-identified principal>'.
Invoke-Sqlcmd: Incorrect syntax was encountered while parsing ''.

检索访问令牌时可能会出现问题,这可能是在使用服务主体身份验证连接 SQL 数据库时出现上述问题的原因。添加服务原理为sql server admin,您可以使用以下代码连接sql数据库:

$clientid = "<SPNcleintId>"
$tenantid = "<SPNtenantId>"
$secret = "<SPNsecret>"
$request = Invoke-RestMethod -Method POST `
           -Uri "https://login.microsoftonline.com/$tenantid/oauth2/token"`
           -Body @{ resource="https://database.windows.net/"; grant_type="client_credentials"; client_id=$clientid; client_secret=$secret }`
           -ContentType "application/x-www-form-urlencoded"
$Token = $request.access_token
$Params = @{
    ServerInstance = '<serverName>.database.windows.net'
    Database = '<databaseName>'
    AccessToken = $Token
}

Invoke-Sqlcmd @Params -Query 'select * from <tableName>'

连接成功如下图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.