它需要从PowerShell代码连接到SQL服务器,并获得每个数据库恢复和他们的大小.
$SqlServer = "localhost\SQL2019";
$SqlLogin = "user1";
$SqlPassw = "user1"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SqlServer; User ID=$SqlLogin; Password=$SqlPassw;"
$SqlConnection.Open()
$SqlCmd = $SqlConnection.CreateCommand()
$SqlCmd.CommandText = "SELECT name
FROM sys.databases"
$objReader = $SqlCmd.ExecuteReader()
while ($objReader.read()) {
Write-Output $objReader.GetValue(0)
}
$objReader.close()
此实际脚本显示了在此SQL Server上恢复的所有数据库的名称。
另一个可以显示数据库大小的脚本是:
SELECT
CONCAT(CAST(SUM(
CAST( (size * 8.0/1024) AS DECIMAL(15,2) )
) AS VARCHAR(20)),' MB') AS [database_size]
FROM sys.database_files;
实际上,我尝试使用在上一个脚本中获得的值创建一个数组,并像这样遍历该数组以获得每个db的大小:
$SqlServer = "localhost\SQL2019";
$SqlLogin = "user1";
$SqlPassw = "user1"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SqlServer; User ID=$SqlLogin; Password=$SqlPassw;"
$SqlConnection.Open()
$SqlCmd = $SqlConnection.CreateCommand()
$SqlCmd.CommandText = "SELECT name
FROM sys.databases"
$objReader = $SqlCmd.ExecuteReader()
while ($objReader.read()) {
foreach($dbs in $objReader.GetValue(0)){
$dbsArr = @($dbs)
$objReader.close()
for ($i = 0; $i -lt $dbsArr.Count; $i++) {
$SqlCmd1 = $SqlConnection.CreateCommand()
$SqlCmd1.CommandText = "use $dbsArr[$i]
SELECT
CONCAT(CAST(SUM(
CAST( (size * 8.0/1024) AS DECIMAL(15,2) )
) AS VARCHAR(20)),' MB') AS [database_size]
FROM sys.database_files;"
$objReader = $SqlCmd.ExecuteReader()
while ($objReader.read()) {
Write-Output $objReader.GetValue(0)
}
}
}
}
$objReader.close()
但对我没用!
请建议如何获得数据库名称和大小可能在1次迭代(1次查询)。谢谢!
1条答案
按热度按时间flvtvl501#
您可以使用DBATOOLS模块来实现这一点