Execute Sql Stored Procedure From Powershell With Parameters
$connString = "Data Source=192.192.192.192\SQL2008,1433;Initial Catalog=MYDATABASE;User Id=SQLUSER; Password=PASSWORD;"
 
$FromDate = Read-Host "Enter Start Date (MM-DD-YYYY)"
$ToDate = Read-Host "Enter End Date (MM-DD-YYYY)"
 
$QueryText = "exec dbo.usp_GenerateMyReport '01-01-2012', '04-04-2012'"
 
$SqlConnection = new-object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $connString
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = "EXEC dbo.usp_GenerateMyReport @FromDate, @ToDate"
 
# Add parameters to pass values to the stored procedure
$SqlCommand.Parameters.AddWithValue("@FromDate", $FromDate) | Out-Null
$SqlCommand.Parameters.AddWithValue("@ToDate", $ToDate) | Out-Null
 
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
 
Write-Host $DataAdapter.Fill($dataset) ' records have been exported.'
 
$dataset.Tables[0] | Export-CSV C:\MyReport.csv -Force
 
Write-Host 'New report C:\MyReport.csv has been successfully generated'
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License