尊敬的Stackoverflow朋友:
我从Microsoft文章“ https://docs.microsoft.com/en-us/azure/sql-database/sql-database-file-space-management”获得的脚本存在问题,它是用于计算每个数据库的已分配空间和已用空间的PowerShell脚本。我需要定期检查弹性池的大小,以确保可以进行数据库克隆。
关于此命令的身份验证方法“ Invoke-Sqlcmd -ServerInstance $ serverFqdn -Database $ database.DatabaseName -Username $ userName -Password $ password -Query $ sqlCommand”。我想默认的身份验证方法是针对SQL数据库用户的,该用户是在数据库内部创建的帐户。但是老板要求我使用Azure Active Directory(AAD)帐户或服务原理。我已尽力使用域帐户,但无法正常使用。总是会产生登录失败错误,如下所示:
2019-12-10T01:04:06.7785144Z At D:\a\_temp\80a23d17-9a10-4d09-a2d9-8fcfbdb3914b.ps1:65
char:10
2019-12-10T01:04:06.7785735Z + (Invoke-Sqlcmd -ServerInstance $serverFqdn -Database
```
My modified version of Microsoft script is as following: (I removed the credentials for safety purpose)
echo "Install Az module"
Install-Module -Name Az -Force -Verbose -Scope "CurrentUser" -AllowClobber
echo "Install sqlServer module"
Install-Module -Name "SqlServer" -AcceptLicense -Force -Verbose -Scope "CurrentUser" -AllowClobber
echo "Import SqlServer modules"
Import-Module SqlServer -Version 21.1.18179
$resourceGroupName = "AHC-DEV-WU-DataPipeline"
$serverName = "aaa"
$poolName = "ahdevdplusdbpool-ads"
$userName = "xxxxx-acab-4b27-a44e-xxxxx" (this is the service principle ID)
$password = "xxxxx_tqSY0FxxxxxxxfqZ" (this is the service principle password)
$tenantId="xxxxxx831-64a12xxxxx8da" (this is our azure account tenant ID)
##$pscredential = Get-Credential Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId
$passwd = ConvertTo-SecureString $password -AsPlainText -Force
$pscredential = New-Object System.Management.Automation.PSCredential($userName, $passwd)
Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId
# get list of databases in elastic pool
$databasesInPool = Get-AzSqlElasticPoolDatabase -ResourceGroupName $resourceGroupName -ServerName $serverName -ElasticPoolName $poolName
$databaseStorageMetrics = @()
# $userName2="svc_xxxx@xxxx.onmicrosoft.com" (this is the domain user account)
# $password2="_4xxxxx" (domain user account password)
# for each database in the elastic pool, get space allocated in MB and space allocated unused in MB
foreach ($database in $databasesInPool) {
$sqlCommand = "SELECT DB_NAME() as DatabaseName, `
SUM(size/128.0) AS DatabaseDataSpaceAllocatedInMB, `
SUM(size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0) AS DatabaseDataSpaceAllocatedUnusedInMB `
FROM sys.database_files `
GROUP BY type_desc `
HAVING type_desc = 'ROWS'"
$serverFqdn = "tcp:" + $serverName + ".database.windows.net,1433"
$databaseStorageMetrics = $databaseStorageMetrics +
(Invoke-Sqlcmd -ServerInstance $serverFqdn -Database $database.DatabaseName `
-Credential $pscredential -Query $sqlCommand -Verbose)
}
# display databases in descending order of space allocated unused
Write-Output "`n" "ElasticPoolName: $poolName"
Write-Output $databaseStorageMetrics | Sort -Property DatabaseDataSpaceAllocatedUnusedInMB -Descending | Format-Table
>