Labels

Saturday, December 1, 2012

Working with xp_cmdshell

xp_cmdshell executes Operating system command through SQL.
Syntax:
EXEC xp_cmdshell {'command_string'} [, no_output]

command_string:
        type here operating system commands.

no_output:
        if no_output is specified, it will not return values. By default it returns 0(Success) or 1(Failure).

How to enable xp_cmdshell:

EXEC sp_configure 'show advanced options',1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO


Example:


EXEC xp_cmdshell 'ver'
EXEC xp_cmdshell 'ipconfig'
EXEC xp_cmdshell 'vol'
EXEC xp_cmdshell 'dir'

Now lets play more with it.
--create a textfile and write some content into it
EXEC xp_cmdshell 'echo hello, this is a text msg >h:\test.txt'
--now read it
EXEC xp_cmdshell 'type h:\test.txt'
--make a newdirectory
EXEC xp_cmdshell 'md h:\to'
--copy this textfile 'test.txt' to another location
EXEC xp_cmdshell 'copy h:\test.txt h:\to\copied.txt'
--now see newlycreated directory and check presense of your copied file
EXEC xp_cmdshell 'dir h:\to'
--now read againfrom copied location for verification
EXEC xp_cmdshell 'type h:\to\copied.txt'
--rename this file
EXEC xp_cmdshell 'ren h:\to\copied.txt renamed.txt'
--delete this file
EXEC xp_cmdshell 'del h:\to\renamed.txt'
--and removedirectory too
EXEC xp_cmdshell 'rd h:\to\'