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
No comments:
Post a Comment