从 SSMS 执行 powershell

execute powershell from SSMS

我正在尝试执行某些 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

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

使用& 逐字 - 按照您的意图 - URL & 是必须包含在 "..." 中的部分(cmd.exe 仅识别 引号) 您必须 ^-转义&:

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

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