Search code examples
powershellhttpwebrequest

Invoke-WebRequest with dynamic host fails


I want to execute a web request with host defined by a parameter:

$serverHost = "myhost"
Invoke-WebRequest http://$serverHost:1234/service -Method Get

Powershell complains about this with the following error:

Invoke-WebRequest : Cannot bind parameter 'Uri'. Cannot convert value "http:///service" to type "System.Uri". Error: "Invalid URI: The hostname could not be parsed."

What do I have to do to get PowerShell to correctly interpret my URL?


Solution

  • PowerShell simply does not resolve the variable within your URL. You are trying to query the service at the URI http://$serverHost:1234/service which won't work. You could do

    $serverHost = "myHost"
    $service = "http://$serverHost`:1234/service"
    Invoke-WebRequest $service -Method Get
    

    (please note that the Backtick ` is required in order to escape the colon).