Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include ampersands in a powershell command in a batch file?

I am trying to download a Google sheet via a batch file. This works:

powershell -Command "Invoke-WebRequest https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?exportFormat=tsv -OutFile output.tsv"

When I specify which sheet/tab I want by adding &gid=1234, this breaks:

powershell -Command "Invoke-WebRequest https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?exportFormat=tsv&gid=1234 -OutFile output.tsv"

The error is:

The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.

How do I wrap the ampersand in quotes without breaking the outer quotes for the Command parameter?

like image 342
Sarah Northway Avatar asked Feb 28 '19 01:02

Sarah Northway


People also ask

What does the ampersand do in PowerShell?

The ampersand tells PowerShell to execute the scriptblock expression. In essence, it's telling PowerShell that the stuff between the curly braces is code and to run it as code. Like functions, you can pass "parameters" to scriptblocks also known as arguments.

Can you use && in PowerShell?

One of the new features in PowerShell 7 are the && and || operators to chain pipelines based on conditions. These operators are known in PowerShell as pipeline chain operators. They work very simply. The && operator would execute the right-hand pipeline if the left-hand pipeline succeeded.

How do I get out of the ampersand in CMD?

When working at the command line or with batch files, you must take one of two actions when you use strings that contain an ampersand. Either you must escape the ampersand by using the caret (^) symbol, or you must enclose the string inside quotation marks.


1 Answers

The URL embedded inside the "..." string passed to powershell -Command must be quoted too, because an unquoted & has special meaning to PowerShell too (though in Windows PowerShell it is currently only reserved for future use; in PowerShell Core it can be used post-positionally to run a command as a background job).

The simplest option is to use embedded '...' quoting, as suggested by Olaf, because ' chars. don't need escaping inside "...". '...' strings in PowerShell are literal strings, which is fine in this case, given that the URL contains no variable references.

powershell -Command "Invoke-WebRequest 'https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?exportFormat=tsv&gid=1234' -OutFile output.tsv"

If embedded "..." quoting is needed for string interpolation, use \" (sic) to escape the embedded (") chars. (note that inside PowerShell, you'd need to use `" or "" instead):

powershell -Command "Invoke-WebRequest \"https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?exportFormat=tsv&gid=1234\" -OutFile output.tsv"
like image 147
mklement0 Avatar answered Sep 26 '22 11:09

mklement0