Created
November 26, 2021 12:52
-
-
Save ehrnst/e34b54d61718405552839532db48734c to your computer and use it in GitHub Desktop.
Query Azure SQL server using PowerShell and access token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## This will use your Azure access token and establish a connection to your Azure SQL instance. | |
## useful when testing network connections or similar | |
$token = Get-AzAccessToken -Resource "https://database.windows.net" | |
# connect to database | |
$dbConn = New-Object System.Data.SqlClient.SqlConnection | |
$dbConn.ConnectionString = "Server=tcp:my-sql-server.database.windows.net,1433;Initial Catalog=myDB;Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;" | |
$dbConn.AccessToken=$token.Token | |
$dbConn.Open() | |
# construct command | |
$dbCmd = New-Object System.Data.SqlClient.SqlCommand | |
$dbCmd.Connection = $dbConn | |
$dbCmd.CommandText = "SELECT * FROM sys.database_principals" | |
# fetch all results | |
$dataset = New-Object System.Data.DataSet | |
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter | |
$adapter.SelectCommand = $dbCmd | |
$adapter.Fill($dataset) | |
# display results | |
$dataset.Tables | Format-Table |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment