powershellazure-active-directoryazure-sql-databasedatabase-connectionsmo

Authenticate with Azure AD account while using Read-SqlTableData to read AzSQL tables


What other properties does one need to add to the ConnectionContext while connecting to AzSQL using an AzAD account?

$srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') "<>.database.windows.net"
$srv.ConnectionContext.LoginSecure = $false
$srv.ConnectionContext.Authentication = [Microsoft.SqlServer.Management.Common.SqlConnectionInfo+AuthenticationMethod]::ActiveDirectoryPassword
$srv.ConnectionContext.Login = "<>@<>.onmicrosoft.com"
$srv.ConnectionContext.Password = "<>"
$srv.ConnectionContext.Connect()

Error : MethodInvocationException: Exception calling "Connect" with "0" argument(s): "Failed to connect to server <>.database.windows.net."

The ActiveDirectoryPassword method works fine from SSMS. I'm trying to run Read-SqlTableData instead of invoking a TSQL query.

Read-SqlTableData -InputObject $srv.Databases["TestDB"].Tables["TestTable"] -TopN 5

Expecting screenshot or screenclip GIF that the answer code is working for an AzAD userid on AzSQL using Read-SqlTableData.


Solution

  • An AccessToken parameter has been added to the cmdlet in version 22.0.59 of the SqlServer Module.

    Read-SqlTableData -AccessToken (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token `
    -ServerInstance <>.database.windows.net -SchemaName dbo -DatabaseName <> -TableName <> -TopN 3 |FT
    

    Output enter image description here