从powershell向多个实例上的SQL查询添加列

时间:2016-05-09 18:15:41

标签: sql-server powershell

我有以下powershell脚本,它读入服务器列表,并在这些服务器上运行SQL命令。然后将此数据导出为csv和excel格式

我希望能够将我的服务器列表中的目标服务器名称添加为第一列,因此列看起来像这样(服务器名称添加到前面)

服务器名称|名称| CollectionSet ID |收集模式|保留期|时间表

这是我目前的剧本:

Param
(    
    [string]$fServers = 'W:\Theo\Scripts\mdw_servers.csv'
)
$query = "SELECT  a.name AS 'DC Name',
        collection_set_id AS 'Collection_set ID',
        CASE collection_mode
          WHEN 1 THEN 'non-cached'
          WHEN 0 THEN 'cached'
        END AS 'Collection Type' ,
        days_until_expiration AS 'Retention Period' ,
        b.name AS 'Schedule Name'
FROM    msdb.dbo.syscollector_collection_sets a ,
        msdb.dbo.sysschedules b
WHERE   a.schedule_uid = b.schedule_uid
        AND is_running = 1;"

$csvFilePath = "W:\Theo\Scripts\queryresults.csv"
$excelFilePath = "W:\Theo\Scripts\queryresults.xls"

# Run Query against multiple servers, combine results


$allServers = Get-Content -Path $fServers

foreach ($Server in $allServers) { 

        write-host "Executing query against server: " $Server
        $results += Invoke-Sqlcmd -Query $query -ServerInstance $Server; 
} 

# Output to CSV

write-host "Saving Query Results in CSV format..." 
$results | export-csv  $csvFilePath   -NoTypeInformation


# 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

任何输入都表示赞赏!

1 个答案:

答案 0 :(得分:1)

你试过吗

SELECT @@SERVERNAME AS 'Server Name'

https://msdn.microsoft.com/en-us/library/ms187944.aspx