I'm trying to do an API call in PowerShell. The problem is that the call contains a "$" and PowerShell interprets that as a variable, and it also contains a real variable it looks something like this:
Is there a way how I can make it so $format is not interpreted, but $foo is?
(I need the "" around $foo)
I already solved this by just splitting it up into two string and then adding them together, but this seems very unstable to me.
CodePudding user response:
I'd strongly recommend construct your uri from multiple parts:
# define base uri
$baseUri = "http://foo.example/bar()"
# define individual query parameters
$queryParameters = [ordered]@{
'$format' = 'json'
'filter' = 'id eq "{0}"' -f $foo
}
# concatenate query parameters
$paramString = $queryParameters.GetEnumerator().ForEach({
$_.Key,$_.Value -join '='
}) -join '&'
# construct full URL from base parameter string
$apicall = $baseUri,$paramString -join '?'
The '
single-quotes around $format
will prevent any attempt at variable expansion.
The literal "
's are preserved in the filter string by also using '
to define a string formatting template, but then using the -f
operator (which will expand $foo
before applying).
This approach obviously requires more source code, but it makes it easier to maintain the URI parameters.
If everything but the $foo
value is static, you can also use an expandable here-string literal (@"
instead of @'
) with a $
character, simply escape it using a backtick:
$apicall = @"
http://foo.example/bar()?`$format=json&filter=id eq "$foo"
"@