Problem
I am unable to use an Environment Variable as a token in an Invoke-RestMethod
I have the following code, that does work:
$props = @{
Uri = $my_url
Method = "POST"
ContentType = "application/json"
Headers = @{ Authorization = "Bearer Token123456789" }
}
$payload = Invoke-RestMethod @props
But I don't want the token hard-coded here.
However, if I replace Token123456789
with the environment variable $env:token
which contains the identical token, it fails.
$props = @{
Uri = $my_url
Method = "POST"
ContentType = "application/json"
Headers = @{ Authorization = "Bearer $env:token" }
}
$payload = Invoke-RestMethod @props
The error message is
Invoke-RestMethod : Specified value has invalid Control characters.
Parameter name: value
At C:\Temp\test.ps1:29 char:12
$payload = Invoke-RestMethod @props
- CategoryInfo : NotSpecified: (:) [Invoke-RestMethod], ArgumentException
- FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
What I have tried
I have tried comparing them directly, like this
$bearer1 = "$env:token"
$bearer2 = "Token123456789"
echo $bearer1
echo $bearer2
echo ($bearer1 -eq $bearer2)
The first two echo's output the same results.
However, the last one returns False
Conclusion
The Environment Variable for some reason does not equal its string equivalent.
How do I turn the environment variable into this identical string so that it will work in my Invoke-RestMethod
?