2016-05-09 8 views
1

私は、サーバのリストを読み込み、これらのサーバでSQLコマンドを実行する次のpowershellスクリプトを用意しています。このデータは、その後、CSV形式にエクスポートされ、私は列は次のようになりますので、最初の列として私のサーバーのリストから対象のサーバー名を追加できるようにしたいフォーマットpowershellの複数のインスタンスでSQLクエリにカラムを追加する

を得意とする(サーバ名が先頭に追加)

サーバー名|名前|コレクションセット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

あなたは...私は混乱ルートを取る理由は時々私は不思議ソリューションが実際にあったかの単純な私を思い出させるためのおかげで

SELECT @@SERVERNAME AS 'Server Name' 

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

+0

を試してみました! ahaは完璧に働いた。 – choloboy

+0

問題ありません:) – quemeful

関連する問題