1. Simple script to run query and save it to file
$fileName = 'FILE_PATH'
$SQLServer = "SERVER_NAME"
$SQLDBName = "DATABASE_NAME"
$userid ="USER_NAME"
$password = "PASSWORD"
$delimiter = ";"
$SqlQuery = "SELECT * FROM TABLE_NAME";
#SQL Query
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $userid; Password = $password;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
#Dataset and save to file
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | export-csv -Delimiter $delimiter -Path $fileName -NoTypeInformation
No comments:
Post a Comment