Tuesday, February 11, 2014

Powershell: Eexecute .sql files using Batch script and without Batch script.

Execute sql script using invoke-sqlcmd with batch script and without batch script.

Option1: using Import sqlps
1.Save sql script as "C:\scripts\Test.sql"
  script in side Test.sql: select name from sys.databases

2.Save Batch script as "C:\scripts\MyTest.bat"
Script inside Batch script:
  powershell.exe C:\scripts\mypowershell.ps1
3.Save powershell script as "C:\scripts\mypowershell.ps1"

 import-module "sqlps" -DisableNameChecking
 invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
4.Run the Batch script commandline or double click then can able to see the output "C:\scripts\TestOutput.txt" file.
5.Connect to current scripts location
  cd C:\scripts (enter)
  C:\scripts\dir (enter )
  C:\scripts\MyTest.bat (enter)
 Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt".

Option2: Otherway, import sqlps and execution
1.Save sql script as "C:\scripts\Test.sql"
  script in side Test.sql: select name from sys.databases

2.Save powershell script as "C:\scripts\mypowershell.ps1"

 # import-module "sqlps" -DisableNameChecking #...Here it not required.
 invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"

3.Connect to current scripts location
  cd C:\scripts (enter)
  C:\scripts\dir (enter )
  C:\scripts\powershell.exe sqlps C:\scripts\mypowershell.ps1  (enter)
 Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt".