Powershell script to run SQL queries

Here's a PowerShell script that connects to a SQL database, runs a SELECT statement, and exports the results to a CSV file:


# Load the SQL Server Management Objects (SMO) assembly [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null # Define the SQL Server connection string $connectionString = "Server=serverName;Database=databaseName;Integrated Security=True" # Connect to the SQL Server database $server = New-Object Microsoft.SqlServer.Management.Smo.Server("serverName") $server.ConnectionContext.ConnectionString = $connectionString # Define the SQL query $query = "SELECT * FROM tableName" # Run the query and store the results in a DataTable $dataTable = New-Object System.Data.DataTable $dataTable.Load($server.ConnectionContext.ExecuteWithResults($query).Tables[0].CreateDataReader()) # Export the results to a CSV file $dataTable | Export-Csv -Path "QueryResults.csv" -NoTypeInformation



This script uses the SQL Server Management Objects (SMO) assembly to connect to a SQL Server database and run a SELECT statement. 
The results of the query are stored in a DataTable and then exported to a CSV file named "QueryResults.csv". 
You'll need to modify the connection string, server name, database name, and query to match your specific requirements.


No comments:

Post a Comment