Try using Invoke-SqlCmd
cmdlet from the SqlServer
module with an Azure AD access token.
- Ensure the Azure SQL Database is Configured for Azure AD Authentication
- Enable Azure AD authentication on your Azure SQL Database.
- Add the Managed Identity (System-assigned or User-assigned) as a user in the database with the necessary permissions.
- Authenticate the Managed Identity
Use theConnect-AzAccount
cmdlet to ensure your PowerShell session is running under the Managed Identity or obtain the token directly usingGet-AzAccessToken
. - Ensure Required Modules are Installed
Install theAz
andSqlServer
modules if not already installed:Install-Module -Name Az -Scope CurrentUser -Force Install-Module -Name SqlServer -Scope CurrentUser -Force
- Generate an Access Token for Azure SQL
Use the following command to fetch an access token for Azure SQL Database:$token = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token
- Use the Access Token with
Invoke-SqlCmd
Pass the token as part of the connection string:Invoke-SqlCmd -ServerInstance "<your_server_name>.database.windows.net" ` -Database "<your_database_name>" ` -AccessToken $token ` -Query "SELECT TOP 10 * FROM YourTable"
Ensure the Managed Identity has been granted Database User Access with roles like db_datareader
, db_datawriter
, or db_owner
, as needed.
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin