【发布时间】: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-SqlCmdPowerShell cmdlet。您必须直接使用sqlcmd.exe工具,以便可以使用[-G use Azure Active Directory for authentication]参数,而Invoke-SqlCmdcmdlet 不会公开该参数。有关示例,请参见 Azure AD token - sqlcmd。
标签: sql-server azure powershell