My task is to retrieve the users list from our Azure SQL databases. We have 100s of Azure SQL database and I want to use PowerShell to make the task fast.
I am using connection string (Active Directory Integrated). I believe I am able to login to the SQL database using the connection string with PowerShell.
However, I am getting an error while running the SQL. Below is the code and exception. Could you please help me?
Code:
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.ParserExceptionat ManagedBatchParser.Parser.Parse()
at Microsoft.SqlServer.Management.PowerShell.ExecutionProcessor.ExecuteTSql(String sqlCommand)
Invoke-SqlCmdfrom theSQLPSmodule? I don't believe it has a-ConnectionStringparameter. TryGet-Help Invoke-SqlCmd.-Server,-ServerInstanceand-Databaseparameters. It's just a wrapper around thesqlcmd.execommand line tool so can basically do (most of) whatever that tool can do.Invoke-SqlCmdPowerShell cmdlet. You'll have to use thesqlcmd.exetool directly so you can use its[-G use Azure Active Directory for authentication]parameter, which theInvoke-SqlCmdcmdlet doesn't expose. See Azure AD token - sqlcmd for an example.