Stubborn Ampersand with Invoke-Webrequest SQL & Powershell

北城以北 提交于 2021-01-28 11:43:22

问题


When I run powershell using invoke-webrequest on a URL without an ampersand everything works.

But my URL's have ampersands in them. If I surround them by double quotes it works from PowerShell, but not if I am doing it through my SQL Server.

Trying to get the right combination of escape characters is proving to be a pain in the butt. Here's an example of the command:

exec xp_cmdshell 'powershell Invoke-WebRequest -UseBasicParsing -Uri "https://example.com/getfile/12345&i=123" -outfile C:\Downloads\test.txt'

It is the ampersand on the &i=123 that is the issue.

If I change the ampersand in the -URI parameter to "&" it does not work. If I prefix with the gravy carat (little ` above tab) it doesn't work. I have also tried to replace it with %26.

Racking my brain here for hours. Any suggestions?


回答1:


Add embedded "..."-quoting to the URL, which requires escaping as \"...\":

exec xp_cmdshell 'powershell Invoke-WebRequest -UseBasicParsing -Uri "\"https://example.com/getfile/12345&i=123\"" -outfile C:\Downloads\test.txt'

This is necessary, because PowerShell's CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell [Core] v6+), when used with the (implied) -Command (-c) option[1]:

  • first removes "..." quoting around individual command-line arguments...
  • and then joins the stripped arguments with spaces and then interprets the resulting string as a PowerShell command line - and at that point quoting around the URL is required, because & is a PowerShell metacharacter.

[1] Note that pwsh now defaults to -File, which expects a script file.



来源:https://stackoverflow.com/questions/65330527/stubborn-ampersand-with-invoke-webrequest-sql-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!