Monday, October 14, 2013

PowerShell Script with multiple Invoke-Sqlcmd calls

People need reports, but I don't like spending too much time putting them together.  That's why I'm looking into using PowerShell to build my reports for me.  I currently use 4 or 5 different SQL queries that hit different servers to acquire numbers for my report.  I'm starting small and hope that by the time I'm done with this script that it will fill in all of the nice bits in an Excel spreadsheet.  So, let's talk about my first snag:

When I began working on this, I found that the best way to get what I needed was to change what SQL scripts I had into scripts that return a single data set.  This means creating temporary tables and filling them with key/value pairs.  Then for the output, I would simply select * from the temporary table.

My next snag was when I needed to add a reference to a second SQL script to my PowerShell script.  I'm calling Invoke-Sqlcmd because the -inputfile parameter allows me to specify a file instead of a single query.  When I ran this, I found that only my first Invoke-Sqlcmd was writing to the screen.  To work around this, I set the result of the Invoke-Sqlcmd to a local variable and then called Format-Table with the new local variable.  Now I have one screen that gives me all of the data I need to throw into my Excel spreadsheet instead of having to go to 2 different SQL scripts.


Add-PSSnapin sqlservercmdletsnapin100
Add-PSSnapin sqlserverprovidersnapin100

$result1 = Invoke-Sqlcmd -inputfile "UsageCount.sql" -Server "server1"
$result2 = Invoke-Sqlcmd -inputfile "Incidents.sql" -Server "server2"

Write-Host "-----------------"
Write-Host
Format-Table -inputobject $result1
Format-Table -inputobject $result2

No comments:

Post a Comment