1

I'm trying to create a script that uses an URL as parameter. Those URLs often have ampersands &. When trying to give an URL with an ampersand I get the following error:

.\test.ps1 -link http://testurl&qdfq
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quot
ation marks ("&") to pass it as part of a string.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : AmpersandNotAllowed

I understand that I can workaround this with using double quotes in the string for example:

.\test.ps1 -link "http://testurl&qdfq"

But I don't understand that the $link parameter needs this, as it is defined as as a string:

param (
    [Parameter(Mandatory=$true)]
    [string]$link
)

Write-information $link -informationaction Continue

Is there another parameter I need to use in stead of [string] to make the command works without double quotes? So I can use:

.\test.ps1 -link http://testurl&qdfq
Jeff Seb
  • 21
  • 5
  • [Escape the ampersand](https://stackoverflow.com/a/16622542/1701026)? `.\test.ps1 -link http://testurl%26qdfq` – iRon Jul 26 '22 at 10:32
  • 2
    You might also use single quotes: `.\test.ps1 -link 'http://testurl&qdfq'` – iRon Jul 26 '22 at 10:35
  • Thx @iRon, though I'm trying to make the script more user friendly so people don't have to use escape chars, or single/double quotes. – Jeff Seb Jul 26 '22 at 11:52
  • 1
    don't tag spam. Version-specific tags are only used for problems only occur in those version. Please remove the irrelevant tags – phuclv Jul 26 '22 at 12:48

1 Answers1

2

& is a PowerShell metacharacter: a character with special meaning when used in unquoted contexts.

Therefore, to use it verbatim, you must:

  • either: individually escape it, with ` (the so-called backtick, PowerShell's escape character):
.\test.ps1 -link http://testurl`&qdfq  # Note the ` before q
.\test.ps1 -link 'http://testurl&qdfq'

I'm trying to make the script more user friendly so people don't have to use escape chars, or single/double quotes

  • There is no way to avoid the techniques above: you must satisfy PowerShell's syntax rules in order to make a successful call.

  • The only way to avoid escaping or quoting would be to prompt for the URL interactively, either explicitly via Read-Host or implicitly, if you declare the target parameter as Mandatory and the user doesn't pass a value in a given invocation.

mklement0
  • 382,024
  • 64
  • 607
  • 775