连接到SQL Server并使用PowerShell代码检索数据库名称和大小

owfi6suc  于 2022-12-13  发布在  Shell
关注(0)|答案(1)|浏览(122)

它需要从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次查询)。谢谢!

flvtvl50

flvtvl501#

您可以使用DBATOOLS模块来实现这一点

Install-Module dbatools -Scope CurrentUser #only once

Get-DbaDatabase -SqlInstance $Sql|select Name, SizeMB

相关问题