$TaskName = "20071029-AllRejectedDuring" $SqlServer = "SQLDEV01"; $SqlCatalog = "MyData"; # Get the T-SQL Query from .SQL file $SqlQuery = Get-Content (".\" + $TaskName + ".sql") #Write-Host ($SqlQuery) -foregroundcolor "gray" # Setup SQL Connection $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True" # Setup SQL Command $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $SqlQuery $SqlCmd.Connection = $SqlConnection # Setup .NET SQLAdapter to execute and fill .NET Dataset $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet #Execute and Get Row Count $nRecs = $SqlAdapter.Fill($DataSet) Write-Host ($nRecs.ToString() + " Records retrieved.") -foregroundcolor "Cyan" $SqlConnection.Close(); if ($nRecs -gt 0) { # Do Stuff $DataSet.Tables[0].Rows[0][0] #Print first data element }
The connection is using Integrated Security for simplicity, it wouldn't be difficult to switch to UID/PWD instead. Also, I put the SQL in a .sql file (flat text) to make life easier; you could also put the statement in the string declaration, if it is a simple query. PowerShell's Get-Content mechanism makes reading a file very easy. Also, clean up after yourself, I won't include that here.
UPDATE: I have posted a full script to export to Excel or XML in a followup post.
Remember Me
b, blockquote@cite, i, strike, strong, u
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.