0

PowerShell to redirect the below command output to a text file:

$tables = invoke-sqlcmd –ServerInstance $SQLServer -Database $DatabaseName -Username $Username -Password $Password  -InputFile $filename.fullname  | Out-String
Delliganesh Sevanesan
  • 4,146
  • 1
  • 5
  • 15

1 Answers1

0
$dbName="DatabaseName"

$instanceName="ServerInstanceName"

$filePath="OutputFilePath"

$query = "SELECT name FROM sys.Tables"

$tableNames = Invoke-SqlCmd –ServerInstance $instanceName -Database $dbName –Query $query

New-Item -Path $filePath -ItemType directory

foreach($TName in $tableNames)

{

$fileileName=$filePath + "\\" + $TName.get_Item(0).ToString() + ".txt"

$getTableData="select * from " + $TName.get_Item(0).ToString()

Invoke-SqlCmd –ServerInstance $instanceName -Database $dbName –Query $getTableData | Export-Csv -Path $fileName -NoTypeInformation

}

Fig. Export DB Table data into a text file

Please Refer: Click here for more info

Delliganesh Sevanesan
  • 4,146
  • 1
  • 5
  • 15
  • Actually I need to execute One or more sql files from a folder . Need to get the Output like Each statement it needs to pick from sql file and get the output whether the statement is inserted or updated or alter database etc.. I need to read each statement in a sql file and print the output accordingly. – raja sekhar reddy Jul 01 '21 at 14:08
  • For all the statement I need to look in each sql file and print the values according to the statement to the console Output.SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index Thanks in Advance – raja sekhar reddy Jul 01 '21 at 14:17
  • Please update the original question or post a new question with updated requirement. If my answer has helped you kindly upvote and accept it as a answer to help the other community members. Thanks – Delliganesh Sevanesan Jul 02 '21 at 09:49
  • Hi Delliganesh , .Actually I need to execute One or more sql files from a folder using powershell . Need to get the Output like Each statement it needs to pick from sql file and get the output whether the statement is inserted or updated or alter database etc.. I need to read each statement in a sql file and print the output accordingly. – raja sekhar reddy Jul 02 '21 at 13:24
  • Hi raja sekhar reddy, I understood but your question is different to the original requirement. Kindly modify your question or post a new question. Thank you. – Delliganesh Sevanesan Jul 03 '21 at 14:42