0

how should I provide to powershell function Uri string with & character, like Get-ValidUri -Uri https://www.youtube.com/watch?v=LZ382nYZPPg&t=421s it always returns error where '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.' I can provide it with double quotes like Get-ValidUri -Uri "https://www.youtube.com/watch?v=LZ382nYZPPg&t=421s" then it works... Thanks in advance !

function Get-WebLinkValid { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateScript({ ({ "{0}" } -f $TestUri).Trim() })] [ValidateNotNullOrEmpty()] [System.UriFormat]$TestUri )

[System.Uri]$Uri = ({ "{0}" } -f $TestUri).Trim()

script

}

  • `[uri]::EscapeDataString('&')` – Doug Maurer Aug 16 '23 at 21:14
  • Thanks, but where to put this one ? – Ivan Benishek Aug 16 '23 at 21:32
  • You can encode your uri to handle special characters. You should clarify what your exact issue is. Your post is poorly formatted and your question unclear. – Doug Maurer Aug 16 '23 at 21:39
  • Okay, simply: function Get-Something { [CmdletBinding()] param ( [uri]$aaa ) #TODO: Place script here } When you pass the parameter like Get-Something efrewfe&erwrew it returns an error. – Ivan Benishek Aug 16 '23 at 21:44
  • 1
    @IvanBenishek - long story short, in Windows PowerShell 5.1, ```&``` is not allowed in "BareWord" tokens (i.e. unquoted strings). You need to wrap it in double-quotes to make it a "DoubleQuoted" token, and then you can use special characters like ```&```, ```space```, etc, as part of the string value. Try this on the command line to see how PowerShell parses the script source: ```{ Get-Something efrewfe }.Ast.EndBlock.Statements[0].PipelineElements[0].CommandElements[1]``` and then quote the string and try again... – mclayton Aug 16 '23 at 23:19
  • Please [format your post properly](https://stackoverflow.com/help/formatting). – mklement0 Aug 16 '23 at 23:36
  • In short: arguments that contains _spaces_ and/or other metacharacters such as `&` must be _quoted_, e.g, `'Program Files'`). See the linked duplicate for details. – mklement0 Aug 16 '23 at 23:39

0 Answers0