Technical Article

Execute VBScript commands or .vbs files via T-SQL.

,

sp_ExecVBScript allows you to execute either a .vbs file or an ad-hoc VBScript command within a T-SQL batch. 

Note that the command (whether it be ad-hoc or contained in the .vbs file) cannot have any code that requires user input (such as Input Boxes or Message Boxes).

/*
Executes either a .vbs file or an ad-hoc VBScript Command.

If executing a file, you must enter full path to file.

Do not attempt to execute code that contains Input boxes, Message Boxes, or any other forum of user input.

EXAMPLES:

EXEC sp_ExecVBScript 'file', 'c:\MyScript.vbs'
EXEC sp_ExecVBScript 'cmd', 'My VBS command'
*/

ALTER  PROCEDURE sp_ExecVBScript
@FileOrCommand VARCHAR(4) = NULL,
@FileCmdText VARCHAR(8000) = NULL

AS

SET NOCOUNT ON

DECLARE @Cmd VARCHAR(8000)

IF @FileOrCommand = 'file'
/* User opts to execute a pre-existing .vbs file */BEGIN

  SET @Cmd = 'EXEC master..xp_cmdshell ''CScript '
  SET @Cmd = @Cmd + '"' + @FileCmdText + '"' + ''''

  EXEC (@Cmd)

END

ELSE IF @FileOrCommand = 'cmd'
/* User opts to execute an ad-hoc VBScript statement */BEGIN

  DECLARE @TempFile SYSNAME
  /* Temporary .vbs file with unique name for holding    VBScript command */
  SELECT @TempFile = 'C:\' + CAST(NEWID() AS SYSNAME) +   N'.vbs' 

  SET @Cmd = 'EXEC master..xp_cmdshell '''
  SET @Cmd = @Cmd + 'ECHO ' + @FileCmdText + ' > ' +   @TempFile + ''''
/* Create and execute .vbs file */  EXEC (@Cmd)

  SET @Cmd = 'EXEC master..xp_cmdshell ''CScript ' + @TempFile + ''''

  EXEC (@Cmd)

  SET @Cmd = 'EXEC master..xp_cmdshell '' DEL ' + @TempFile + ''''
  /* Delete temp file */  EXEC (@Cmd)

END

Rate

5 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

5 (2)

You rated this post out of 5. Change rating