powershell 使用Azure自动化Runbook读取.sql文件

vnjpjtjt  于 2023-06-23  发布在  Shell
关注(0)|答案(1)|浏览(144)

我正在尝试将我的Powershell Runbook连接到存储帐户(blob)以读取.sql文件并在Azure SQL数据库中执行它们。
1.连接到blob容器
1.读取.sql文件上的脚本
1.在数据库上执行脚本
当我尝试Invoke-Sqlcmd时,它需要一个专用存储来存储文件。然而,据我所知,RunBooks是无服务器工作的,而且我没有存储空间可以用于文件。
有没有一种方法可以通过powershell runbook只读取文件(而不移动它们),或者我可以存储文件来读取?

qvtsj1bj

qvtsj1bj1#

您可以使用以下方法执行保存在Azure运行手册中的Azure blob存储中的文件中的SQL。

# The accountName and accountKey are needed to get into the storage account.
# I recommend saving these as credentials in the automation account
$accountName = "xxxxxxxxxxxxx"
$accountKey = "yyyyyyyyyyyyyyyyyyy"
$containerName = "container-name"
$sqlFile = "sql-file.sql"

$context = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey
$container_client = Get-AzStorageContainer -Name $containerName -Context $context
$source_blob_client = $container_client.CloudBlobContainer.GetBlockBlobReference($sqlFile)

#download the blob as text into memory
$sqlFromFile = $source_blob_client.DownloadText()

# The following 'MyCredential' is saved a credential in the automation account   
$SQLServerCred = Get-AutomationPSCredential -Name 'MyCredential'
#Import the SQL Server Name from the Automation variable.
$SQL_Server_Name = "myhsm-db-eu.database.windows.net"
#Import the SQL DB from the Automation variable.
$SQL_DB_Name = "db_name"

# Execute query
invoke-sqlcmd -ServerInstance "$SQL_Server_Name" -Database "$SQL_DB_Name" -Credential $SQLServerCred -Query "$sqlFromFile"

希望这能帮上忙。谢谢

相关问题