Escaping Command Parameters Passed by xp_cmdshell to dtexec

I call the SSIS package remotely using a stored procedure and calling xp_cmdshell:

declare @cmd varchar(5000)
set @cmd = '"C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\dtexec.exe" /Rep E /Sql Package /SET \Package.Variables[User::ImportFileName].Value;c:\foo.xlsx'
print @cmd
exec xp_cmdshell @cmd

This works fine, however, I cannot guarantee that the value of the variable (c: \ foo.xslx) will not contain spaces, so I would like to avoid this with quotes, as shown below:

set @cmd = '"C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\dtexec.exe" /Rep E /Sql Package /SET \Package.Variables[User::ImportFileName].Value;"c:\foo.xlsx"'

But at the same time I get an error

'C:\Program' is not recognized as an internal or external command, operable program or batch file.

Both of these commands work fine if executed in cmd.exe, so I assume that SQL Server interprets my double quotes and changes something, but I can’t figure out what.

+3
source share
2 answers

, CMD /S /C " " . , .

:

declare @cmd varchar(8000)
-- Note you can use CMD builtins and output redirection etc with this technique, 
-- as we are going to pass the whole thing to CMD to execute
set @cmd = 'echo "Test" > "c:\my log directory\logfile.txt" 2> "c:\my other directory\err.log" '


declare @retVal int
declare @output table(
    ix int identity primary key,
    txt varchar(max)
)


-- Magic goes here:
set @cmd = 'CMD /S /C " ' + @cmd + ' " '

insert into @output(txt)
exec @retVal = xp_cmdshell @cmd
insert @output(txt) select '(Exit Code: ' + cast(@retVal as varchar(10))+')'

select * from @output
+3

Source: https://habr.com/ru/post/1765793/


All Articles