Powershell Connect To Azure SQL Database

You can also connect to Azure SQL Database using PowerShell. using the information mentioned in this article below.

Powershell Connect To Azure SQL Database

Below are the prerequisites that you must have before proceeding.

  • To connect to Azure SQL DB using PowerShell, as a prerequisite, you must install the Azure PowerShell module.
  • Now, you need to authenticate to Azure using the Azure PowerShell cmdlet. Once you run the below PowerShell cmdlet, it will prompt you to enter your Azure Credential.
PS C:\WINDOWS\system32> Connect-AzAccount
  • Next, you can use the Azure PowerShell cmdlet below to verify everything works fine.
Get-AzSqlServer -ResourceGroupName <Your Resource Group>
Get-AzSqlServer -ResourceGroupName Demo123

If you run the above PowerShell cmdlet and all is ok, you should get the output like the one below. Check out the screenshot below.

Powershell Connect To Azure SQL Database
ResourceGroupName        : Demo123
ServerName               : test45
Location                 : eastus
SqlAdministratorLogin    : rajkishore
SqlAdministratorPassword : 
ServerVersion            : 12.0
Tags                     : {}
Identity                 : 
FullyQualifiedDomainName : test45.database.windows.net
ResourceId               : /subscriptions/1cdf4300-dee5-4518-9c9c-feaa72a5cbd1/resourc
MinimalTlsVersion        : 
PublicNetworkAccess      : Enabled
  • You can run the below script to import the Azure SQL module and set different parameters like database, username, credentials, and query. You can run Invoke-SqlCmd to initiate the transact SQL query.
Import-Module Az.Sql -Force

$MyParams = @{
   'ServerInstance' = 'demo126.database.windows.net';
   'Database' = 'demo';
   'Username' = 'Rajkishore';
   'Password' = 'Raj@12345';
   'Query' = 'Your select query;'

Invoke-Sqlcmd @MyParams
  • Now, if you want, you can also read the Azure SQL server and DB, and then you can pass the information to the actual query, as shown below
Import-Module Az.Sql -Force
$resourcegrpName = '<Your Resource Group Name>'
$myServerDetails = Get-AzSqlServer -ResourceGroupName $resourcegrpName
$mysqlDB = Get-AzSqlDatabase -ServerName $myServerDetails.ServerName -ResourceGroupName $resourcegrpName 
$MyParams = @{
   'ServerInstance' = $myServerDetails.FullyQualifiedDomainName;
   'Database' = $mysqlDB.DatabaseName[0];
   'Username' = $myServerDetails.SqlAdministratorLogin;
   'Password' = ‘<Password>’;
   'Query' = 'Your SQL Query;'
Invoke-Sqlcmd @MyParams

You may also like following the articles below


This article discussed the quick steps to connect to Azure SQL Database using PowerShell. Thanks for reading this article!!!