Sunday, January 24, 2016

Poweshell/Batch script execute using sql agent job

Using Batch file 
----------------
1.Create D:\Test\TestDBFile.bat file

set log=D:\Test\TestDBFile_Log.txt

Echo %date%.%time%.... Before  rename>>%log%

Rename D:\SQLDATA\SQLDAT\Test.mdf TestOld.mdf >>%log%
Rename D:\SQLLOG\SQLLOG\Test_log.ldf TestOld_log.ldf  >>%log%

Echo %date%.%time%.... After  rename>>%log%

First test "TestDBFile.bat" execute , through command prompt,
if it working then schedule sql agent job( for sql agent job drop down select "Operating System(CMDExec)" option from step in sql agent.
command (give):D:\Test\TestDBFile.bat

2.Using Powershell 
-------------------------

1.Create D:\Test\test.ps1 file with below details

Rename-Item D:\SQLDATA\SQLDAT\Test.mdf TestOld.mdf ;
Rename-Item D:\SQLLOG\SQLLOG\Test_log.ldf TestOld_log.ldf;

2. You can execute with below:
D:\fullpath\powershell.exe -Noninteractive -Inputformat none -Executionpolicy Bypass -Command D:\Test\test.ps1

3.You can schedule sql agent job.


OR

3.Powershell other way using batch script

1.Create D:\Test\test.ps1 file with below details

Rename-Item D:\SQLDATA\SQLDAT\Test.mdf TestOld.mdf ;
Rename-Item D:\SQLLOG\SQLLOG\Test_log.ldf TestOld_log.ldf;

2. Crete D:\Test\TestPowershellscript.bat file

set Pslog=D:\Test\TestPowershellDBFile_Log.txt

Echo %date%.%time%.... Before  rename file using PS>>%PSlog%
D:\fullpath\powershell.exe -Noninteractive -Inputformat none -Executionpolicy Bypass -Command D:\Test\test.ps1

Echo %date%.%time%.... After   rename file using PS>>%log%

3.First test "TestPowershellscript.bat " execute , through command promt,
if it working then schedule sql agent job( for sql agent job drop down selact "Operating System(CMDExec)" option from step in sql agent.
command (give):  D:\Test\TestPowershellscript.bat