-3
我有一個SQL腳本來獲取數據庫大小,我需要在50個SQL服務器上運行它,每個服務器有10個左右的數據庫,併爲每個數據庫獲取報告。我如何使用PowerShell來執行該操作。從powershell執行Sql腳本
所以我的問題是如何從poweshell遠程執行一個SQL腳本,並讓每個數據庫
上輸出。這是我嘗試使用該腳本,我發現它在網上和更新,但它不工作
$dbservers=get-content "c:\powershell\list.txt"
$Cre = Get-Credential -Credential xxxxxxxxxxxxx
ForEach-Object ($s in $dbservers)
{
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$s = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $server
$dbs = $s.Databases
$dbs | SELECT Name -ExpandProperty Name | ForEach-Object{
String]$database = $_
if (($database -ne "master") -and ($database -ne "tempdb") -and ($database -ne "msdb") -and ($database -ne "model")) {
$ServerName = $dbservers
$DatabaseName = $database
$Query = "Create Table ##temp
(
ServerName nvarchar(250),
DatabaseName sysname,
Name sysname,
physical_name nvarchar(500),
size decimal (18,2),
FreeSpace decimal (18,2)
)
Exec sp_msforeachdb '
Use [?];
Insert Into ##temp (ServerName,DatabaseName, Name, physical_name, Size, FreeSpace)
Select @@SERVERNAME ,DB_NAME() AS [DatabaseName], Name, physical_name,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) as nvarchar) Size,
From sys.database_files '
Select *
From ##temp
where DatabaseName not in ('master','tempdb','model','msdb')
drop table ##temp "
#Timeout parameters
$QueryTimeout = 120
$ConnectionTimeout = 30
#Action of connecting to the Database and executing the query and returning results if there were any.
$conn = New-Object System.Data.SqlClient.SQLConnection
$ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerName, $DatabaseName, $ConnectionTimeout
$conn.ConnectionString = $ConnectionString
$conn.Open()
$cmd = New-Object system.Data.SqlClient.SqlCommand($Query, $conn)
$cmd.CommandTimeout = $QueryTimeout
$ds = New-Object system.Data.DataSet
$da = New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[void]$da.fill($ds)
$conn.Close()
$ds.Tables
}
}
}
我收到此錯誤
The following exception was thrown when trying to enumerate the collection: "Failed to connect to server ..".
At C:\Powershell\datafile.ps1:10 char:1
+ <<<< $dbs | SELECT Name -ExpandProperty Name | ForEach-Object{
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : ExceptionInGetEnumerator
謝謝你看我的問題。願你告訴我什麼是得到負面的原因! – sebeid
其實在這種情況下,我不需要在每個數據庫上運行它..我想我可以忽略$ Database變量 – sebeid
「不工作」是什麼意思?你必須給我們一些工作。 –