-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRun-SQLFromAzureBlobStorage.ps1
More file actions
75 lines (62 loc) · 2.54 KB
/
Run-SQLFromAzureBlobStorage.ps1
File metadata and controls
75 lines (62 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
param(
[parameter(Mandatory=$True)]
[string] $SqlServer,
[parameter(Mandatory=$False)]
[string] $SqlServerPort = 1433,
[parameter(Mandatory=$True)]
[string] $Database,
[parameter(Mandatory=$True)]
[string] $Script
)
##########Login##########
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
##########Download SQL script from blob##########
$ResourceGroupName = "automationuems"
$StorageAccountName = "automationuems"
$Container = "scripts"
$Path = "$env:TEMP\$Script"
$StorageAccountKey = Get-AutomationVariable -Name 'StorageAccountKey'
$Ctx = New-AzureStorageContext $StorageAccountName -StorageAccountKey $StorageAccountKey
Get-AzureStorageBlobContent -Container $Container -Blob $Script -Destination $Path -Context $Ctx -Verbose
##########Run SQL script##########
$CmdCommandText = Get-Content $Path
$SqlCredential = Get-AutomationPSCredential -Name "SqlCredentialAsset"
if ($SqlCredential -eq $null)
{
throw "Could not retrieve '$SqlCredentialAsset' credential asset. Check that you created this first in the Automation service."
}
# Get the username and password from the SQL Credential
$SqlUsername = $SqlCredential.UserName
$SqlPass = $SqlCredential.GetNetworkCredential().Password
# Define the connection to the SQL Database
$Conn = New-Object System.Data.SqlClient.SqlConnection("Server=tcp:$SqlServer,$SqlServerPort;Database=$Database;User ID=$SqlUsername;Password=$SqlPass;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;")
# Open the SQL connection
$Conn.Open()
# Define the SQL command to run. In this case we are getting the number of rows in the table
$Cmd=new-object system.Data.SqlClient.SqlCommand($CmdCommandText, $Conn)
$Cmd.CommandTimeout=120
###
$CmdDbResult = $Cmd.ExecuteReader()
$CmdDbResult
$Conn.Close()