Код PowerShell для извлечения данных с нескольких серверов SQL.
Я хотел, чтобы код извлекал данные на основе запроса SQL с нескольких серверов в xls / csv.Запрос SQL и список серверов для динамического извлечения с использованием запроса SQL.
Код:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Management.IntegrationServices") | Out-Null;
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Management.Dac") | Out-Null
Param(
[string] $Instance
)
clear
$instance = ''
$cmsserver = 'Raheesh'
$cmsdb = 'msdb'
$BaseDir = 'C:\data\'
$CsvFilePath = $BaseDir + "queryresults.csv"
$ExcelFilePath = $BaseDir + "queryresults.xls"
$ServerNameFile = $BaseDir + "GetServerList.sql"
$ServerListSql = Get-Content($ServerNameFile)
$BackupFile = $BaseDir + "backup.sql"
$BackupSql = Get-Content($BackupFile) | Out-String
$dt = Get-Date
"$Instance fetch starts at " + $dt +"`r`n" + "`r`n"
# Create your list and place it in a variable using Invoke-Sqlcmd
#Invoke-Sqlcmd -ServerInstance <TheNameOfYourCMSServer> -Database msdb (because that is where CMS is stored) -Query $ServerListQuery
$serverlist = Invoke-Sqlcmd -ServerInstance $cmsserver -Database $cmsdb -Query $ServerListSql | Out-String
$serverlist = $serverlist.ToString()
Write-Host $serverlist
Write-Host "enter 1"
# Loop through the list and run your query
foreach ($instance in $serverlist) {
# remove named instance if it exists for the ping test
$servername = $instance[0].Split("\") | Select-Object -Index 0 | Out-String
Write-Host $servername
Write-Host "enter 2"
if (Test-Connection -BufferSize 32 -Count 1 -ComputerName $servername -Quiet) {
try {
Write-Host "enter 3"
# Run the query variable created at the top $SQLServerVersionQuery
$results = Invoke-Sqlcmd -ServerInstance $instance[0] -Query $BackupSql -QueryTimeout 300 | Out-String
Write-Host "Saving Query Results in CSV format..."
$results | Export-Csv $CsvFilePath -NoTypeInformation
(Get-Content $csvFilePath) | Foreach-Object {
$_ -replace "`"", ""
} | Set-Content $CsvFilePath
# Convert CSV file to Excel
Write-Host "Converting CSV output to Excel..."
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$workbook = $excel.Workbooks.Open($csvFilePath)
$workSheet = $workbook.Worksheets.Item(1)
$resize = $workSheet.UsedRange
$resize.EntireColumn.AutoFit() | Out-Null
$xlExcel8 = 56
$workbook.SaveAs($excelFilePath, $xlExcel8)
$workbook.Close()
$excel.Quit()
$excel = $null
Write-Host "Results are saved in Excel file: " $excelFilePath
"$Instance fetch ends at " + $dt +"`r`n" + "`r`n"
} catch {
# Catch the error if SQL connectino doesn't work
Write-Output "SQL Connect Error on: $instance[0] >> $Error[0]"
}
} else {
# Catch the error if the ping test fails
Write-Output "Server Ping Error: $servername >> $Error[0]"
}
}
Ошибка:
fetch starts at 02/02/2019 11:00:24
ServerName
----------
raheesh
enter 1
Method invocation failed because [System.Char] does not contain a method named 'split'.
At C:\Data\PS_OLD\final.ps1:41 char:5
+ $servername = $instance[0].Split("\") | Select-Object -Index 0 | ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
enter 2
Test-Connection : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Data\PS_OLD\final.ps1:44 char:62
+ ... -Connection -BufferSize 32 -Count 1 -ComputerName $servername -Quiet)
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Test-Connection], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand