【问题标题】:Escaping command parameters passed to xp_cmdshell to dtexec将传递给 xp_cmdshell 的命令参数转义到 dtexec
【发布时间】:2011-04-15 03:09:56
【问题描述】:

我正在使用存储过程和对 xp_cmdshell 的调用远程调用 SSIS 包:

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

这很好用,但是我不能保证变量值 (c:\foo.xslx) 不会包含空格,所以我想用下面的引号来转义它:

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"'

但是这样做我得到了错误

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

如果在 cmd.exe 中执行,上述两个命令都可以正常工作,所以我猜测 SQL Server 正在解释我的双引号并更改某些内容,但我不知道是什么。

【问题讨论】:

    标签: sql tsql sql-server-2008 stored-procedures ssis


    【解决方案1】:

    在调查后,您似乎必须将 DOS 8.3 表示法与 xp_cmdshell 一起使用,例如c:\progra~1... 并且参数上只能有一组引号。

    要解决此限制,请使用旧的 DOS 表示法,或者将代码放入批处理文件中,这样可以正常运行。

    来源:http://social.msdn.microsoft.com/forums/en-US/sqlintegrationservices/thread/4e7024bb-9362-49ca-99d7-1b74f7178a65

    【讨论】:

      【解决方案2】:

      简而言之,将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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-23
        • 1970-01-01
        • 2015-06-09
        • 2017-10-22
        • 2021-10-20
        • 2019-10-12
        • 1970-01-01
        相关资源
        最近更新 更多