0

I am following the example provided in this entry on how to manually build a header to be used on a Invoke-WebRequest.

The sample solution given in the said entry is:

$user = 'user'
$pass = 'pass'

$pair = "$($user):$($pass)"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}

Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

I am having trouble concatenating $user and $pass because the value of $pass contains a double-quote.

How do I correctly concatenate these variables?

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • 3
    Could you elaborate on what do you mean by having trouble? Are you getting any error? – Santiago Squarzon May 17 '21 at 17:50
  • Yes, if you take a look at the sample code I pasted, the variable $pair is used to store the concatenated values of $user, a colon, and $pass. But since the value of $pass contains a double-quote, it is causing powershell to accept that double-quote as the terminator of the string. – LesterTriple7 May 17 '21 at 18:11
  • 2
    @LesterTriple7 The `"` character in your source code would be two lines above (`$pass = ...`), so why would it be interpreted as a string terminator of a string literal starting 2 lines below? Please post a screenshot or error message from whichever tool exhibits this behavior – Mathias R. Jessen May 17 '21 at 18:27

1 Answers1

2

I am unable to replicate this on PS 5.1 and PS Core. As far as I'm aware of, PS should autoresolve the variable expansion for you even if it has ":

$user = 'user.example'
$pass = 'password."example'

$pair = "$user`:$pass"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

Then Base64 decode returns:

PS C:\> [system.text.encoding]::ASCII.GetString([system.convert]::FromBase64String($encodedCreds))
user.example:password."example
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37