【问题标题】:execute powershell from SSMS从 SSMS 执行 powershell
【发布时间】:2022-01-04 19:50:06
【问题描述】:

我正在尝试作为某些 xp_cmdshell 代码执行:

declare @url varchar(250) = 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02'
declare @c varchar(1000) = N'powershell.exe -noprofile -executionpolicy bypass '
  + N'-command (Invoke-WebRequest -Uri '''+@url+'''-UseBasicParsing).content'
    print @c
exec xp_cmdshell @c

但这是我得到的错误:

The string is missing the terminator: '.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
 
'appid' is not recognized as an internal or external command,
operable program or batch file

当我尝试在 powershell 中执行相同的操作时,我得到了预期的响应(见图)

(Invoke-WebRequest -Uri 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02'-UseBasicParsing).content

Powershell

xp_cmdshell 的预期输出应该是 json

【问题讨论】:

  • 你为什么想要首先在SSMS中执行它?
  • 我正在尝试将 API 响应放入表中。我不是 C# 开发人员,我想在 ssms 中使用 sql server 2019 和 json 功能。
  • 然后将数据推送到 SQL Server。调用 Web API 并不是 SQL 的设计目的。使用不同的语言将数据获取到 SQL Server,然后您可以在 SQL Server 中使用它。
  • 如果您想在 SQL Server 中“玩转” JSON,那么只需自己获取 JSON 并将值放入一个变量中以 玩转。不要把xp_cmdshell 塞进去。
  • 旁注,如果您将命令粘贴到命令提示符中(xp_cmdshell 正在使用),you get the same error

标签: sql json powershell api ssms


【解决方案1】:

错误消息暗示您的命令行正在通过cmd.exe 执行,其中& 是一个元字符

要使用& 逐字 - 按照您的意图 - 或者& 所在的 URL 必须包含在 "..." 中(@987654326 @ 只识别引号)你必须^-转义&

declare @url varchar(250) = 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk^&appid=439d4b804bc8187953eb36d2a8c26a02'
-- ...

cmd.exe 解析命令行时,它会将^& 识别为转义 & 以逐字使用,并在传递参数之前删除转义字符^ .

【讨论】:

  • 第三个选项是使用-EncodedCommand 在Base64 中传递命令,但这需要一些额外的步骤。不过,不用担心转义元字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2010-10-24
  • 2014-08-28
  • 1970-01-01
相关资源
最近更新 更多